只能通过id,而不是通过类找到BeautidulSoup4(Python3.x)

时间:2017-08-31 23:26:17

标签: python-3.x selenium beautifulsoup web-crawler html-parsing

我是BeautifulSoup4的新手,遇到了一个看似基本的问题。我只能通过id找到,但不能通过课程找到。例如,我正在查看一个网站,其中包含以下html部分:

enter image description here

现在,以下工作:

page_soup.findAll('div', {'id': 'page-content'})

而以下找不到任何内容:

page_soup.findAll('div', {'class': 'main-container'})

所以我的问题是:是' class'处理不同于' id'属性?如果是这样,按类名搜索的正确方法是什么?

为了完成,虽然我认为无关紧要,但我使用selenium包的page_source方法获取了html。

编辑Here是此类网页的一个示例。如果我们检查上表,包括玩家的位置,年龄等,那么我们得到上面的html快照。

1 个答案:

答案 0 :(得分:1)

以下是我运行的命令,它对我很有用

In [1]: from bs4 import BeautifulSoup

In [2]: import requests

In [3]: res = requests.get("http://www.spotrac.com/mlb/atlanta-braves/freddie-freeman-7359/")

In [4]: soup = BeautifulSoup(res.text,"lxml")

In [5]: len(soup.findAll('div', {'class': 'main-container'}))
Out[5]: 1

In [6]:  soup = BeautifulSoup(res.text,"html5lib")

In [7]: len(soup.findAll('div', {'class': 'main-container'}))
Out[7]: 1

In [8]: import sys; sys.version
Out[8]: '3.6.2 (default, Jul 17 2017, 16:44:45) \n[GCC 4.2.1 Compatible Apple LLVM 8.1.0 (clang-802.0.42)]'

正如您所看到的,它在两个解析器中都适用于我。