首页 > 解决方案 > 如果标签存在于 HTML 中,如何从标签中获取数据,否则如果标签不存在于网络抓取 Python 中,则为空字符串

问题描述

图片包含情况的 HTML 代码

情况1:

<li> 
    <a> some text: </a><strong> 'identifier:''random words' </strong>
</li>

案例2:

<li>
    <a> some text: </a>
</li>

如果存在标识符,我想抓取它的值,否则如果在特定情况下没有标识符,我想放置一个空字符串。我正在使用scrapy,或者您也可以帮助我使用 BeautifulSoup,非常感谢您的帮助

标签: python-3.xweb-scrapingbeautifulsoupscrapy

解决方案


有点不清楚您到底想要什么,因为您的屏幕截图与您问题中的示例略有不同。我想您想搜索文本"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: 

推荐阅读