我试图采取一些信息,我从一个网页和写的变量之一到一个文件,但我没有运气,这可能是非常容易,但我迷路了。下面是其中一行的示例,共有1253行。你知道吗
<div class='entry qual-5 used-demoman slot-head bestprice custom' data-price='3280000' data-name="Kill-a-Watt Allbrero" data-quality="5" data-australium="normal" data-class="demoman" data-particle_effect="56" data-paint="" data-slot="cosmetic" data-consignment="consignment">
我在名为data name的字段后面,它不在每行的同一位置。我试过了,但没用
mfile=open('itemlist.txt','r')
mfile2=open('output.txt','a')
for row in mfile:
if char =='data-name':
mfile2.write(char)
编辑1:
我做了一个“你好,嗨,花生”的示例文件 如果有:
for row in mfile:
print row.index('hello')
它会像预期的那样打印0,但是当我把hello改成hi时,它没有返回1,它什么也没有返回。你知道吗
让我们尝试使用常见的字符串操作方法来查找值:
我们可以使用^{} 来查找字符串在字符串中的位置:
现在我们知道我们需要开始为我们感兴趣的属性寻找索引
87
:现在,我们也需要删除
data-name="
部分:现在,我们只需要找到右引号的索引,然后我们就可以提取属性值:
然后我们有了我们的解决方案:
我们可以把它放在循环中:
也可以使用beautifulsoup:
a.html:
a.py:
我的观点是,如果您的任务像您的示例中那样简单,那么实际上没有必要使用
beautifulsoup
。但是,如果它更复杂,或者它会更复杂。考虑用beautifulsoup
试试。你知道吗相关问题 更多 >
编程相关推荐