【问题标题】:Beatifulsoup doesnt return href it returns NoneBeautifulsoup 不返回 href 它返回 None
【发布时间】:2021-03-01 13:26:48
【问题描述】:
>>> soup_brand
<a data-role="BRAND" href="/URL/somename">
          Some Name
        </a>

>>> type(soup_brand)
<class 'bs4.BeautifulSoup'>

>>> print(soup_brand.get('href'))
None

随后的文档:https://www.crummy.com/software/BeautifulSoup/bs4/doc/

嗨,来自世界各地的人们, 有人现在出了什么问题还是我的目标对象错了?

需要获取href。

【问题讨论】:

    标签: python beautifulsoup


    【解决方案1】:

    你试过了吗:

    soup.find_all(name="a")
    

    soup.select_one(selector="a")
    

    应该也可以赶上

    all_anchor_tags = soup.find_all(name="a")
    for tag in all_anchor_tags:
        print(tag.get("href")) #prints the href element of each a tag, thus each link
    

    虽然我遇到了 all bs4 寻找多个元素(我们在这里有一个循环的原因),但如果你给它一个搜索所有方法然后迭代元素,bs4 有时会更好地捕捉东西

    【讨论】:

      【解决方案2】:

      为了应用['href'],对象必须是&lt;bs4.Element.Tag&gt;

      那么,试试这个:

      string = \
      """
      <a data-role="BRAND" href="/URL/somename">
                Some Name
              </a>
      """
      
      s = BeautifulSoup(string)
      a_tag = s.find('a')
      print(a_tag["href"])
      

      出来

      /URL/somename
      

      或者如果你有多个a标签,你可以试试这个:

      a_tags = s.findAll('a')
      for a in a_tags:
          print(a.get("href"))
      

      出来

      /URL/somename
      

      【讨论】:

      • 谢谢,成功了。感谢您的帮助
      • 很高兴为您提供帮助。
      猜你喜欢
      • 1970-01-01
      • 2021-01-14
      • 2021-12-27
      • 1970-01-01
      • 2019-10-13
      • 2020-09-19
      • 2017-03-01
      • 2020-03-12
      • 2019-11-27
      相关资源
      最近更新 更多