我正在从https://www.basketball-reference.com/players/p/parsoch01.html上抓取课文。但是我不能抓取页面中位于“总计”表下面的内容。我想从“总计”和“高级”表中得到数字,但是代码没有返回任何内容。当用户向下滚动页面时,该页面似乎会加载其他信息。
我运行了下面的代码,并成功地从玩家的个人资料部分和“每个游戏”表中获得数据。但无法从“总计”表中获得值。
from lxml import html
import urllib
playerURL=urllib.urlopen("https://www.basketball-reference.com/players/p/parsoch01.html")
# Use xpath to parse points per game.
ppg=playerPage.xpath('//tr[@id="per_game.2019"]//td[@data-stat="pts_per_g"]//text()')[0]# succeed to get the value
total=playerPage.xpath('//tr[@id="totals.2019"]//td[@data-stat="fga"]//text()')// I expect 182 to be returned but nothing is returned.
有什么方法从这个页面的下部获取数据吗?
发布于 2019-07-26 23:09:55
这是因为你想从那个网站上提取的内容都在评论中。BeautifulSoup不能解析注释中的内容。要获得结果,您需要先取消注释,以便BeautifulSoup可以访问它。下面的脚本完成了我试图说的话:
import requests
from bs4 import BeautifulSoup
URL = "https://www.basketball-reference.com/players/p/parsoch01.html"
r = requests.get(URL).text
#kick out the comment signs from html elements so that BeautifulSoup can access them
comment = r.replace("-->", "").replace("<!--", "")
soup = BeautifulSoup(comment,"lxml")
total = soup.select_one("[id='totals.2019'] > [data-stat='fga']").text
print(total)
输出:
182
发布于 2019-07-26 20:01:14
打开web浏览器的控制台,测试xpath,看看它是否找到要查找的元素。
$x("//tr[@id='totals.2019']//td[@data-stat='fga']//text()")
返回Array对象。
$x("//tr[@id='totals.2019']//td[@data-stat='fga']//text()")[0]
访问所需的值。
另外:
# comments in python start with '#' not '//'
https://stackoverflow.com/questions/57228784
复制相似问题