因此,我尝试使用BeautifulSoup和urllib从特定网站上抓取表格。我的目标是根据此表中的所有数据创建一个列表。我已经尝试过使用其他网站上的表格使用相同的代码,并且效果很好。但是,在此网站上尝试该表时,该表将返回NoneType对象。有人可以帮我弄这个吗?我尝试过在线寻找其他答案,但运气不佳。
这是代码:
import requests
import urllib
from bs4 import BeautifulSoup
soup = BeautifulSoup(urllib.request.urlopen("http://www.teamrankings.com/ncaa-basketball/stat/free-throw-pct").read())
table = soup.find("table", attrs={'class':'sortable'})
data = []
rows = table.findAll("tr")
for tr in rows:
cols = tr.findAll("td")
for td in cols:
text = ''.join(td.find(text=True))
data.append(text)
print(data)
看起来这些数据是通过ajax调用加载的:
您应该定位该网址: http://www.teamrankings.com/ajax/league/v3/stats_controller.php
import requests
import urllib
from bs4 import BeautifulSoup
params = {
"type":"team-detail",
"league":"ncb",
"stat_id":"3083",
"season_id":"312",
"cat_type":"2",
"view":"stats_v1",
"is_previous":"0",
"date":"04/06/2015"
}
content = urllib.request.urlopen("http://www.teamrankings.com/ajax/league/v3/stats_controller.php",data=urllib.parse.urlencode(params).encode('utf8')).read()
soup = BeautifulSoup(content)
table = soup.find("table", attrs={'class':'sortable'})
data = []
rows = table.findAll("tr")
for tr in rows:
cols = tr.findAll("td")
for td in cols:
text = ''.join(td.find(text=True))
data.append(text)
print(data)
使用Web检查器,您还可以查看与POST请求一起传递的参数。
通常,另一端的服务器将检查这些值,如果没有或全部没有这些值,则拒绝您的请求。上面的代码片段对我来说很好。我urllib2
之所以转向,是因为我通常更喜欢使用该库。
如果数据加载到浏览器中,则可以将其抓取。您只需要模仿浏览器发送的请求即可。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句