【发布时间】:2017-01-12 00:21:31
【问题描述】:
我是python新手(使用python3.6),我学习它主要是为了能够为这个页面构建一个爬虫 http://www.nhl.com/stats/player?aggregate=0&gameType=2&report=skatersummary&pos=S&reportType=season&seasonFrom=20162017&seasonTo=20162017&filter=gamesPlayed,gte,1&sort=points,goals,assists
我尝试了很多东西,我原本想尝试使用 xpath,但在失败后,我决定尝试使用 BeautifulSoup4,我收到了这个错误
for row in soup('table', {'class': 'stat-table'})[0].tbody('tr'):
IndexError: list index out of range
从此代码
import urllib.request
from bs4 import BeautifulSoup
soup = BeautifulSoup(urllib.request.urlopen('http://www.nhl.com/stats/player?aggregate=0&gameType=2&report=skatersummary&pos=S&reportType=season&seasonFrom=20162017&seasonTo=20162017&filter=gamesPlayed,gte,1&sort=points,goals,assists'),"lxml")
for row in soup('table', {'class': 'stat-table'})[0].tbody('tr'):
tds = row('td')
print(tds[0].string, tds[1].string)
【问题讨论】:
-
该请求中不存在带有
class="stat-table"的table。该信息是动态的。检查“javascript 渲染”。 -
是的,当我意识到它是 javascript 时,我知道我需要一种不同的方法。 wu4m4n 的答案完美无缺,但我还将研究“javascript 渲染”以了解更多信息。谢谢!
标签: python python-3.x xpath web-scraping lxml