我是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)
最佳答案
为了使它起作用,您必须找到向内部API发出请求的正确URL。
要获取网址,您必须使用Google chrome的网络控制台。
1)打开控制台,然后单击“网络”
2)然后刷新网站,您将看到此页面上的所有请求。
3)然后,您必须通过“ XHR”进行过滤,然后就可以了!
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import requests
import lxml.html
from pprint import pprint
from sys import exit
import json
import csv
url = 'http://www.nhl.com/stats/rest/grouped/skaters/basic/season/skatersummary?cayenneExp=seasonId=20162017 and gameTypeId=2&factCayenneExp=gamesPlayed>=1&sort=[{"property":"points","direction":"DESC"},{"property":"goals","direction":"DESC"},{"property":"assists","direction":"DESC"}]'
resp = requests.get(url).text
resp = json.loads(resp)
pprint(resp['data'])