【问题标题】:How to find an html tag without an id or class name using BeautifulSoup?如何使用 BeautifulSoup 查找没有 id 或类名的 html 标签?
【发布时间】:2020-02-05 23:40:24
【问题描述】:

当一个 html 标签有一个与之关联的 id 时,我可以访问它的内容,但是找不到没有 id 的 html 标签。

当 id 存在时,我可以访问我需要的内容:

<div id="anything"> 
  <div class="anything">
  What I need
  </div>
</div>

但如果标签看起来像这样:

<div id="anything">
  <div>
    <div class="something">
      What I need 
    </div>
  </div>
</div>

我无法使用 .findAll、.find_next_sibling 或 .children 找到它 我尝试通过以下方式找到它:

x = soup.find('div', attrs ={'id':'anything'}) 
type(x.div) 
print(x.div.text)

但是 type(x.div) 返回 NoneType....???

for foo in soup.find_all('div', attrs={'id': 'anything'}):
    bar = foo.find('div', attrs={'class': 'anything'})
    print(bar.contents[0].text)

这会在第一个 html 块中打印“我需要什么”,而不是第二个

这适用于带有 ID 的标签,但我无法找到一种方法来查找没有 ID 的 div

【问题讨论】:

  • 只要去掉attrs参数,它就会找到所有的DIV。
  • 如果有很多 div (~100),那么在 find_all DIV 之后如何找到我正在寻找的那个(没有 id 或 class 的 DIV)?
  • 你要找的标准是什么?
  • 在上面的 html 示例中,我需要的文本位于
    标记内,但该标记位于没有 id 或类的
    标记内。我无法从
    解析到
    并最终解析到
    看起来只是一个错字。第二个电话应该是{'class': 'something'},而不是{'class': 'anything'}

标签: python html python-3.x beautifulsoup


【解决方案1】:

您可以像这样向下导航 div 链:

print(soup.div.div.text)

输出:

  What I need 

【讨论】:

  • 这只是整个html的一小部分,所以我不能一直附加.div。我试图保存这个值:x = soup.find('div', attrs ={'id':'anything'}) 然后使用 print(x.div.text),但是 type(x.div) = NoneType
【解决方案2】:

我想知道我是否在这里遗漏了什么。您可以使用 select 以及带有 id 的父级和带有类的子级之间的关系

from bs4 import BeautifulSoup as bs

html = '''<div id="anything">
  <div>
    <div class="something">
      What I need 
    </div>
  </div>
</div>'''

soup = bs(html, 'lxml')
print(soup.select_one('#anything .something').text.strip())

【讨论】:

    猜你喜欢
    • 2020-03-03
    • 1970-01-01
    • 2013-06-15
    • 2020-03-04
    • 2013-09-18
    • 2019-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多