【问题标题】:search div with id and same classes搜索具有 id 和相同类的 div
【发布时间】:2020-09-11 11:16:51
【问题描述】:

我想搜索以不同 id 开头但类相同的 html div:

<div id="alabama" class="sc-fzoxKX fmCwKG state-entry">
<div id="alaska" class="sc-fzoxKX fmCwKG state-entry">

我尝试使用

containers = page_soup.findAll("div", {"class":"sc-fzoxKX fmCwKG state-entry"})

但是当我通过编写len(containers) 进行测试时,它返回 0。 我也试过containers[0],但它返回的索引超出范围错误。

谁能告诉我如何搜索列表?

【问题讨论】:

标签: python html beautifulsoup


【解决方案1】:

在查找多个类时,您应该使用class_ 作为find_all 的参数。完整的功能代码:

from bs4 import BeautifulSoup

htmltxt = '<div id="alabama" class="sc-fzoxKX fmCwKG state-entry"></div><div id="alaska" class="sc-fzoxKX fmCwKG state-entry"></div>'
page_soup = BeautifulSoup(htmltxt, 'html.parser')
container = page_soup.find_all("div", class_ = "sc-fzoxKX fmCwKG state-entry")

print(len(container)) # Gives 2
print(container) # Gives the two divs

# To get the respective ids of all the divs:
for div in container:
  print(div.get('id'))

另见:Difference between "findAll" and "find_all" in BeautifulSoup

如果您使用的是不应该使用的 Beautiful Soup 3(将其更新到版本 4),find_all 将不起作用,您必须像在原始代码中那样使用 findAll。但是,这两个函数名称都适用于 bs4

附:我在你的两个 div 中添加了结束 &lt;/div&gt; 标记。

【讨论】:

  • '''len(container)''' 仍然返回 0 :'(
  • 哦,我已经编辑了我的帖子。请检查这是否是您的问题。你用的是哪个版本的美汤?
  • 不幸的是,len(container) 仍然返回 0。我认为这是我放入 findAll 的命令的问题。我应该解决id吗?还是上课就够了?
  • @mayiango 我将完整代码放入我的答案中并对其进行了测试。请仔细检查一次,如果不是,请使用find_all
  • 此代码适用于您的作品! :) 但是,当我将 page_soup 指定给网站时:cnn.com/interactive/2020/us/states-reopen-coronavirus-trnd 代码再次不起作用。你能帮我看看这个网站的html代码吗?我认为代码失败可能是由于这个特定网站的 html 结构。我正在研究在每个州下提取信息。提前谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-23
  • 2021-12-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多