【问题标题】:Extracting href from 'a' element with text only attribute从具有纯文本属性的“a”元素中提取href
【发布时间】:2020-12-20 20:19:21
【问题描述】:

我正在尝试在 python webscraper 中构建一个函数,该函数将移动到结果列表中的下一页。由于链接位于许多其他标签的末尾,并且没有任何属性,例如类或 ID,因此我无法在美丽的汤中找到该元素。

这是 html 的 sn-p:

<a href="http://www.url?&=page=2">
     Next
    
   </a>

我一直在阅读 bs4 文档,试图了解如何提取 URL,但我遇到了困难。我认为它可以通过以下任一方式完成:

  1. 在父元素中找到最后一个 .a['href'],因为它始终是最后一个。
  2. 根据始终包含“Next”文本的事实来查找 href

我不知道怎么写可以解决 1. 或 2.

我的思路正确吗?有没有人有任何建议来实现我的目标?谢谢

【问题讨论】:

    标签: python beautifulsoup


    【解决方案1】:

    要查找包含文本Next&lt;a&gt; 标签,您可以:

    from bs4 import BeautifulSoup
    
    
    txt = '''
    <a href="http://www.url?&=page=2">
         Next
        
       </a>'''
    
    
    soup = BeautifulSoup(txt, 'html.parser')    
    print(soup.select_one('a:contains("Next")')['href'])
    

    打印:

    http://www.url?&=page=2
    

    或者:

    print(soup.find('a', text=lambda t: t.strip() == 'Next')['href'])
    

    要获取某个元素内的最后一个&lt;a&gt; 标签,您可以使用[-1] 索引ResultSet

    from bs4 import BeautifulSoup
    
    
    txt = '''
    <div id="block">
        <a href="#">Some other link</a>
        <a href="http://www.url?&=page=2">Next</a>
    </div>
    '''
    
    
    soup = BeautifulSoup(txt, 'html.parser')
    
    print(soup.select('div#block > a')[-1]['href'])
    

    【讨论】:

    • 谢谢,解决了!特别是 print(soup.select_one('a:contains("Next")')['href'])
    猜你喜欢
    • 1970-01-01
    • 2011-04-18
    • 2019-09-16
    • 2012-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-04
    相关资源
    最近更新 更多