无论我尝试使用BeautifulSoup4都无法找到表

时间:2019-01-26 21:53:03

标签: python pandas beautifulsoup

我正在尝试同时从一个网页上抓取2张桌子。 BeautifulSoup可以找到第一个表没有问题,但是无论我如何尝试都找不到第二个表,这里是网页:Hockey Reference: Justin Abdelkader

这是季后赛标题下面的表格。

这是我的代码。

        sauce = urllib.request.urlopen('https://www.hockey-reference.com/players/a/abdelju01/gamelog/2014', timeout=None).read()
        soup = bs.BeautifulSoup(sauce, 'html5lib')
        table = soup.find_all('table')
        print(len(table))

始终打印1。

如果我打印(汤),并在终端中使用搜索功能,则可以找到2个单独的表格标签。我没有看到任何会阻碍BS4查找标签的JavaScript。我也尝试过通过id和class查找表,即使表的父div似乎也是找不到的。有谁知道我可能做错了什么?

4 个答案:

答案 0 :(得分:2)

由于javascript正在加载其他信息

今天requests_html可以加载html页面和javascript内容。

pip install requests-html

from requests_html import HTMLSession
session = HTMLSession()
r = session.get('https://www.hockey-reference.com/players/a/abdelju01/gamelog/2014')
r.html.render()
res = r.html.find('table')
print(len(res))
4

答案 1 :(得分:1)

第二个表似乎在HTML注释标签<--... <table class=...中。我想这就是BeautifulSoup找不到它的原因。

答案 2 :(得分:1)

该表看起来像是一个小部件-单击“共享和更多”->“嵌入此表”,您将获得带有链接的脚本:

https://widgets.sports-reference.com/wg.fcgi?css=1&site=hr&url=%2Fplayers%2Fa%2Fabdelju01%2Fgamelog%2F2014&div=div_gamelog_playoffs

我们如何解析它?

import requests
import bs4
url = 'https://widgets.sports-reference.com/wg.fcgi?css=1&site=hr&url=%2Fplayers%2Fa%2Fabdelju01%2Fgamelog%2F2014&div=div_gamelog_playoffs'
widget = requests.get(url).text
fixed = '\n'.join(s.lstrip("document.write('").rstrip("');") for s in widget.splitlines())

soup = bs4.BeautifulSoup(fixed)
soup.find('td', {'data-stat': "date_game"}).text # => '2014-04-18'

Voila!

答案 3 :(得分:1)

您可以通过bs4评论到达评论行,例如:

from bs4 import BeautifulSoup , Comment
from urllib import urlopen


search_url = 'https://www.hockey-reference.com/players/a/abdelju01/gamelog/2014'

page = urlopen(search_url)
soup = BeautifulSoup(page, "html.parser")

table = soup.findAll('table') ## html part with no comment
table_with_comment = soup.findAll(text=lambda text:isinstance(text, Comment))
[comment.extract() for comment in table_with_comment]
## print table_with_comment  print all comment line

start = '<table class'

for c in range(0,len(table_with_comment)):
    if start in table_with_comment[c]:
         print table_with_comment[c] ## print comment line has <table class