首页 > 解决方案 > 在beautifulsoup中的同一h1标签中从下一个跨度中抓取数据

问题描述

嗨,我正在尝试抓取子类别

subcat = soup.find(class_='bread-block-wrap').find(class_='breadcrumb-keyword-bg').find(class_='breadcrumb-keyword list-responsive-container').find(class_='ui-breadcrumb').find('h1')

这是输出

<h1>
<a href="//www.aliexpress.com/category/509/cellphones-telecommunications.html" title="Cellphones &amp; Telecommunications"> Cellphones &amp; Telecommunications</a>
<span class="divider">&gt;</span> <span> Mobile Phones</span>
</h1>

所以现在有 2 个跨度标签编号 1 是

<span class="divider">&gt;</span>

第二个是

<span> Mobile Phones</span>

我想在第二个跨度标签中刮掉这个文本,请有人帮忙

标签: pythonweb-scrapingbeautifulsoup

解决方案


您可以使用find_all()函数获取列表中的所有跨度标签,然后使用.text属性获取文本。

subcat.find_all('span')[1].text

应该输出

 Mobile Phones

演示

from bs4 import BeautifulSoup
html="""
<h1>
<a href="//www.aliexpress.com/category/509/cellphones-telecommunications.html" title="Cellphones &amp; Telecommunications"> Cellphones &amp; Telecommunications</a>
<span class="divider">&gt;</span> <span> Mobile Phones</span>
</h1>
"""
soup=BeautifulSoup(html,'html.parser')
h1=soup.find('h1')
print(h1.find_all('span')[1].text.strip())

输出

Mobile Phones

推荐阅读