gpt4 book ai didi

Python web scraping - 如何在页面通过JS加载内容时获取资源?

转载 作者:太空狗 更新时间:2023-10-30 00:49:27 24 4
gpt4 key购买 nike

所以我正在尝试使用 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 调用加载的:

enter image description here

您应该改为定位该网址: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)

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

enter image description here

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

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

关于Python web scraping - 如何在页面通过JS加载内容时获取资源?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29753717/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com