python - 如何使用 BeautifulSoup 查找没有 id 或类名的 html 标签?

标签 python html python-3.x beautifulsoup

当 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 block 中打印“我需要什么”,但不会在第二个中打印

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

最佳答案

您可以像这样沿着 div 链导航:

print(soup.div.div.text)

输出:

  What I need 

关于python - 如何使用 BeautifulSoup 查找没有 id 或类名的 html 标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58290513/

相关文章:

python - 通过起始字符选择元组中的元素

python - 为什么 zip 函数没有给出 python 中的预期结果

python - 如何从嵌入的字典/列表中提取所有值?

python - Google Cloud Dataflow 从字典写入 CSV

javascript - 视频中的 HTML5 Canvas drawImage 未在第一次绘制时显示

javascript - 多个复选框 > 至少应显示一条必填项,否则会显示错误消息

python - 为什么这个 Python ascii 字符串不等于常规字符串?

python爬虫ieee论文关键词

python - virtualenv 下的 Django runserver 使用错误版本

javascript - mb_YTPlayer - 无法在 div 中插入 YouTube 视频