【问题标题】:How to select multiple children from HTML tag with Python/BeautifulSoup if exists?如果存在,如何使用 Python/BeautifulSoup 从 HTML 标记中选择多个子项?
【发布时间】:2023-01-16 23:22:21
【问题描述】:
我目前正在从网页中抓取元素。假设我正在遍历 HTML 响应,该响应的一部分如下所示:
<div class="col-sm-12 col-md-5">
<div class="material">
<div class="material-parts">
<span class="material-part" title="SLT-4 2435">
<img src="/images/train-material/mat_slt4.png"/> </span>
<span class="material-part" title="SLT-6 2631">
<img src="/images/train-material/mat_slt6.png"/> </span>
</div>
</div>
</div>
我知道我可以像这样访问 span 类中 title 下的第一个元素:
row[-1].find('span')['title']
"SLT-4 2435
但我也想选择 span 类(如果存在)下的第二个 title 作为字符串,如下所示:"SLT-4 2435, SLT-6 2631"
有任何想法吗?
【问题讨论】:
标签:
python
html
css
web-scraping
beautifulsoup
【解决方案1】:
您可以使用 find_all() 函数查找所有 span 类为 material-part 的元素
titles = []
for material_part in row[-1].find_all('span', class_='material-part'):
titles.append(material_part['title'])
result = ', '.join(titles)
【解决方案2】:
除了find() / find_all(),您还可以使用css selectors:
soup.select('span.material-part[title]')
,将ResultSet与list comprehension和join()迭代为单个字符串:
','.join([t.get('title') for t in soup.select('span.material-part[title]')])
例子
from bs4 import BeautifulSoup
html = '''<div class="col-sm-12 col-md-5">
<div class="material">
<div class="material-parts">
<span class="material-part" title="SLT-4 2435">
<img src="/images/train-material/mat_slt4.png"/> </span>
<span class="material-part" title="SLT-6 2631">
<img src="/images/train-material/mat_slt6.png"/> </span>
</div>
</div>
</div>'''
soup = BeautifulSoup(html)
','.join([t.get('title') for t in soup.select('span.material-part[title]')])
输出
SLT-4 2435,SLT-6 2631