Python网页抓取 - 当页面通过JS加载内容时,如何通过美丽的汤获取资源?

QwE*_*y99 5 python screen-scraping urllib beautifulsoup

所以我试图使用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)
Run Code Online (Sandbox Code Playgroud)

Far*_*Joe 4

看起来这个数据是通过 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)
Run Code Online (Sandbox Code Playgroud)

使用 Web 检查器,您还可以查看随 POST 请求一起传递的参数。

在此输入图像描述

通常,另一端的服务器会检查这些值,如果您没有部分或全部值,则拒绝您的请求。上面的代码片段对我来说运行良好。我切换到这个库是urllib2因为我通常更喜欢使用该库。

如果数据加载到您的浏览器中,则可以抓取它。您只需要模仿浏览器发送的请求即可。