美丽的汤不能找到标签

时间:2017-07-02 04:21:43

标签: python beautifulsoup

我目前正在尝试使用Python 3.6中的请求和BeautifulSoup模块进行练习,并遇到了一个我无法在其他问题和答案中找到任何信息的问题。

似乎在页面的某个时刻,Beuatiful Soup停止识别标签和ID。我试图从这样的页面中提取播放数据:

http://www.pro-football-reference.com/boxscores/201609080den.htm

import requests, bs4

source_url = 'http://www.pro-football-reference.com/boxscores/201609080den.htm'
res = requests.get(source_url)
if '404' in res.url:
    raise Exception('No data found for this link: '+source_url)

soup = bs4.BeautifulSoup(res.text,'html.parser')

#this works
all_pbp = soup.findAll('div', {'id' : 'all_pbp'})
print(len(all_pbp))

#this doesn't
table = soup.findAll('table', {'id' : 'pbp'})
print(len(table))

在Chrome中使用检查器,我可以看到该表肯定存在。我也尝试在HTML的后半部分使用它,并且它似乎无法正常工作。我已经尝试过标准' html.parser'以及lxml和html5lib,但似乎没有任何效果。

我在这里做错了什么,或者HTML或其格式中是否存在阻止BeautifulSoup正确查找以后标签的内容?我遇到过这家公司(hockey-reference.com,basketball-reference.com)运营的类似网页的问题,但是能够在其他网站上正确使用这些工具。

如果它是HTML的内容,是否有更好的工具/库可以帮助提取这些信息?

感谢您的帮助, BF

2 个答案:

答案 0 :(得分:2)

在执行网址的GET请求后,BS4将无法执行网页的javascript。我认为关注表是从客户端javascript加载异步。

因此,在抓取HTML之前,需要先运行客户端javascript。这个post描述了如何做到这一点!

答案 1 :(得分:0)

好的,我得到的是什么问题。您正在尝试解析 comment ,而不是普通的html元素。 对于此类情况,您应使用Comment中的BeautifulSoup,如下所示:

import requests
from bs4 import BeautifulSoup,Comment

source_url = 'http://www.pro-football-reference.com/boxscores/201609080den.htm'
res = requests.get(source_url)
if '404' in res.url:
    raise Exception('No data found for this link: '+source_url)

soup = BeautifulSoup(res.content,'html.parser')

comments=soup.find_all(string=lambda text:isinstance(text,Comment))

for comment in comments:
    comment=BeautifulSoup(str(comment), 'html.parser')
    search_play = comment.find('table', {'id':'pbp'})
    if search_play:
        play_to_play=search_play
相关问题