python - 在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 & Telecommunications"> Cellphones & Telecommunications</a>
<span class="divider">></span> <span> Mobile Phones</span>
</h1>
所以现在有 2 个跨度标签编号 1 是
<span class="divider">></span>
第二个是
<span> Mobile Phones</span>
我想在第二个跨度标签中刮掉这个文本,请有人帮忙
解决方案
您可以使用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 & Telecommunications"> Cellphones & Telecommunications</a>
<span class="divider">></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
推荐阅读
- android - Flutter 显示和隐藏 AlertDialog 取决于动态值
- javascript - 箭头函数示例
- laravel - 如何使用 laravel 中的会话绑定表中列的详细信息
- dynamics-crm - 如何从 Flow 中的 Order Product 列表中获取特定数据?
- javascript - 使用 getElementByClassName 切换颜色更改不起作用
- git - 从(但不写入)生产环境读取数据的测试环境
- r - 如何从 R 中的 state.x77 数据集中获取州名
- excel - 如何根据另一个单元格颜色设置单元格颜色
- java - 运行导出的 jar 时缺少 JavaFX 运行时组件
- g1ant - Google OCR 插件 G1ANT Studio