【问题标题】:findAll returning empty for htmlfindAll 返回空的 html
【发布时间】:2017-05-12 14:59:12
【问题描述】:

我正在使用BeautifulSoup 模块来解析我想从中提取某些信息的html 文件。特别是比赛成绩和球队名称。

但是,当我使用 findAll 函数时,它会不断地为肯定在 html 中的字符串返回空值。如果有人可以解释我做错了什么,将不胜感激。请参阅下面的代码。

import urllib
import bs4
import re
from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as soup

my_url = 'http://www.foxsports.com/mlb/scores?season=2017&date=2017-05-09'
uClient = uReq(my_url)
page_html = uClient.read()
uClient.close()
# html parser
page_soup = soup(page_html, "html.parser")
container = page_soup.findAll("div",{"class":"wisbb_teams"})
print(len(container))

【问题讨论】:

  • wisbb_teams 的文字似乎根本没有出现在 my_url 的 HTML 中。
  • 抓取成功了吗?

标签: python html parsing beautifulsoup findall


【解决方案1】:

我认为您使用的语法是 BeautifulSoup 的旧版本,请尝试使用 find_all snake_case 之类的语法(参见 docs

from bs4 import BeautifulSoup
# ...
page_html = uClient.read()
page_soup = BeautifulSoup(page_html, "html.parser")
list_of_divs = page_soup.find_all("div", class_="wisbb_name")
print(len(list_of_divs))

较旧的 API 使用 CamelCase,但 bs4 使用的是 snake_case

另外,注意 find_all 可以接受 class_ 参数以按 class 查找。

查看这个答案,https://stackoverflow.com/a/38471317/4443226,了解更多信息

另外,请确保您正在寻找正确的类名!我没有看到您要查找的课程,而是以下这些:

【讨论】:

  • 嘿,谢谢!我能问一下您是如何找到包含 wisbb 的潜在类的吗?另外,至少当我检查页面上的元素时,存在这样的类。你知道为什么会这样吗?我想要的信息嵌套在 html 中的许多类中,这可能是我找不到它的原因吗?
  • 我只是通过使用 firefox 检查控制台并搜索该字符串 wisbb 获得了该图像 :) 我没有看到任何 wisb_teams
猜你喜欢
  • 1970-01-01
  • 2017-08-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-01
  • 2020-04-16
相关资源
最近更新 更多