Jer*_*oen 5 html python beautifulsoup web-scraping python-3.6
假设有以下 html 片段,我想从中提取与标签“price”和“ships from”相对应的值:
<div class="divName">
<div>
<label>Price</label>
<div>22.99</div>
</div>
<div>
<label>Ships from</label>
<span>EU</span>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
这是较大的 html 文件的一部分。假设在某些文件中存在“发货自”标签,有时不存在。由于 html 内容的可变性,我想使用类似方法的 BeautifulSoup 来处理这个问题。多个div和span存在,这使得在没有 id 或类名的情况下很难选择
我的想法,是这样的:
t = open('snippet.html', 'rb').read().decode('iso-8859-1')
s = BeautifulSoup(t, 'lxml')
s.find('div.divName[label*=Price]')
s.find('div.divName[label*=Ships from]')
Run Code Online (Sandbox Code Playgroud)
但是,这将返回一个空列表。
使用select查找label然后使用find_next_sibling().text
前任:
from bs4 import BeautifulSoup
html = """<div class="divName">
<div>
<label>Price</label>
<div>22.99</div>
</div>
<div>
<label>Ships from</label>
<span>EU</span>
</div>
</div>"""
soup = BeautifulSoup(html, "html.parser")
for lab in soup.select("label"):
print(lab.find_next_sibling().text)
Run Code Online (Sandbox Code Playgroud)
输出:
22.99
EU
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1928 次 |
| 最近记录: |