【问题标题】:How to get data from a tag if it's present in HTML else Empty String if the tag is not present in web scraping Python如果标签存在于 HTML 中,如何从标签中获取数据,否则如果标签不存在于网络抓取 Python 中,则为空字符串
【发布时间】:2020-06-25 19:24:59
【问题描述】:

Picture contains HTML code for the situation

案例一:

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

案例2:

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

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

【问题讨论】:

    标签: python-3.x web-scraping beautifulsoup scrapy


    【解决方案1】:

    有点不清楚您到底想要什么,因为您的屏幕截图与您问题中的示例略有不同。我想您想搜索文本"some text:",然后在&lt;strong&gt; 中获取下一个值(如果没有,则为空字符串):

    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: 
    

    【讨论】:

    • 感谢这工作正常! '感恩'和scrapy有什么相同的方法吗?
    • @dashkandhar 我根本不使用scrapy,但我可以想象你可以将scrapy和bs4结合在一起。
    • 是的!这就是我现在正在尝试的,非常感谢您的及时回复!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-16
    • 2017-10-22
    • 2013-11-08
    • 1970-01-01
    • 2012-11-07
    • 1970-01-01
    相关资源
    最近更新 更多