python - BeautifulSoup 网络爬虫问题 : can't find certain divs/tables

标签 python web-scraping beautifulsoup

我在抓取 pro-football-reference.com 时遇到问题。我正在尝试访问“Team Offense”表,但似乎无法定位到 div/表。 我能做的最好的是:

soup.find('div', {'id':'all_team_stats})

它不返回表格,也不是直接的 div 包装器。以下尝试返回“无”:

soup.find('div', {'id':'div_team_stats'})
soup.find('table', {'id':'team_stats'})

我已经通过以下方式抓取了不同的页面:

soup.find('table', {'id':'table_id})

但我不明白为什么它在这个页面上不起作用。下面是我一直在使用的代码。非常感谢任何帮助!

from bs4 import BeautifulSoup
import urllib2

def make_soup(url):
    page = urllib2.urlopen(url)
    soupdata = BeautifulSoup(page, 'lxml')
    return soupdata

def get_player_totals():
    soup = make_soup("http://www.pro-football-reference.com/years/2015/")

    tableStats = soup.find('table', {'id':'team_stats'})

    return tableStats

print get_player_totals()

编辑:

感谢大家的帮助。下面提供的两种解决方案均已成功。非常感谢!

最佳答案

在传递给 bs4 之前,只需使用 re.sub 删除评论:

from bs4 import BeautifulSoup
import urllib2
import re
comm = re.compile("<!--|-->")
def make_soup(url):
    page = urllib2.urlopen(url)
    soupdata = BeautifulSoup(comm.sub("", page.read()), 'lxml')
    return soupdata

def get_player_totals():
    soup = make_soup("http://www.pro-football-reference.com/years/2015/")

    tableStats = soup.find('table', {'id':'team_stats'})

    return tableStats

print get_player_totals()

您将在运行代码时看到表格。

关于python - BeautifulSoup 网络爬虫问题 : can't find certain divs/tables,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39602223/

相关文章:

Python RegEx 与 Beautifulsoup 4 不起作用

Python十进制转二进制递归

google-sheets - 如何在 Google 表格中获取消费者价格指数 (CPI)?

python - beautifulsoup解析html标签异常

html - 当我尝试查询其他国家/地区的es-es时,抓取news.google.com将hl和ceid参数添加为en-us

python - “PipeTransport”对象没有属性 '_output' - 错误

python - 所需项目不在汤对象中 - BeautifulSoup Python

Python:只想拆分列表中项目的最后一个括号

c++ - 如何使用 Crypto++ 在 C++ 中解密字符串数据,其中使用 pyCrypto 在 Python 中加密的原始字符串

python - 更新文本中的标记词