我正在尝试从网页上获取一些信息并将其中一个变量写入文件但是我没有运气它可能很容易但我迷路了。以下是其中一行有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它没有返回任何内容。
答案 0 :(得分:3)
让我们尝试使用常见的字符串操作方法找到值:
>>> line = '''<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">'''
我们可以使用str.index
来查找字符串中字符串的位置:
>>> line.index('data-name')
87
现在我们知道我们需要开始查看我们感兴趣的属性的索引87
:
>>> line[87:]
'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="
部分:
>>> start = line.index('data-name') + len('data-name="')
>>> start
98
>>> line[start:]
'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">'
现在,我们只需要找到右引号的索引,然后我们就可以只提取属性值:
>>> end = line.index('"', start)
>>> end
118
>>> line[start:end]
'Kill-a-Watt Allbrero'
然后我们有了解决方案:
start = line.index('data-name') + len('data-name="')
end = line.index('"', start)
print(line[start:end])
我们可以把它放在循环中:
with open('itemlist.txt','r') as mfile, open('output.txt','a') as mfile2w
for line in mfile:
start = line.index('data-name') + len('data-name="')
end = line.index('"', start)
mfile2.write(line[start:end])
mfile2.write('\n')
答案 1 :(得分:1)
您还可以使用beautifulsoup:
<强> a.html 强>:
<html>
<head>
<title> Asdf </title>
</head>
<body>
<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">
</body>
</html>
<强> a.py 强>:
from bs4 import BeautifulSoup
with open('a.html') as f:
lines = f.readlines()
soup = BeautifulSoup(''.join(lines), 'html.parser')
result = soup.findAll('div')[0]['data-price']
print result
# prints 3280000
我的意见是,如果您的任务非常简单,那么实际上不需要使用beautifulsoup
。但是,如果它更复杂,或者它会更复杂。考虑尝试使用beautifulsoup
。