python-3.x - 如果标签存在于 HTML 中,如何从标签中获取数据,否则如果标签不存在于网络抓取 Python 中,则为空字符串
问题描述
情况1:
<li>
<a> some text: </a><strong> 'identifier:''random words' </strong>
</li>
案例2:
<li>
<a> some text: </a>
</li>
如果存在标识符,我想抓取它的值,否则如果在特定情况下没有标识符,我想放置一个空字符串。我正在使用scrapy,或者您也可以帮助我使用 BeautifulSoup,非常感谢您的帮助
解决方案
有点不清楚您到底想要什么,因为您的屏幕截图与您问题中的示例略有不同。我想您想搜索文本"some text:"
,然后在其中获取下一个值<strong>
(如果没有,则为空字符串):
from bs4 import BeautifulSoup
txt = '''
<li>
<a> some text: </a><strong> 'identifier:''random words' </strong>
</li>
<li>
<a> some text: </a>
</li>
'''
soup = BeautifulSoup(txt, 'html.parser')
for t in soup.find_all(lambda t: t.contents[0].strip() == 'some text:'):
identifier = t.parent.find('strong')
identifier = identifier.get_text(strip=True) if identifier else ''
print('Found:', identifier)
印刷:
Found: 'identifier:''random words'
Found:
推荐阅读
- node.js - 有什么方法可以识别 NodeJS 中的 SQL Server 存储过程返回的错误
- flutter - Flutter:谷歌创始之选
- django - 如何在 django 3.1 中执行允许 DELETE 方法的基于类的删除视图?
- c# - dotnet-trace 不解析 linux-arm 下的符号
- linux - 如何找到使用 _do_fork() 创建新进程的基本例程?
- javascript - 为什么在向上和向下缩放容器后将指针向下事件传递给错误的 PIXI.Container?附上测试用例
- javascript - 如何根据值使猫鼬模式动态化?
- python - 为什么 QTableView 有空白边距,我该如何删除它们?
- php - Wordpress 自定义小部件显示在错误的位置
- python - 使用机器人阅读 Discord 频道消息