我正在尝试通过网络抓取多个曲棍球网站,以返回比分和球队名称。我正在使用request和phantomjs来提取html,并使用美汤来解析数据。然而,对于下面的网站,当我使用request或phantomjs来获取html代码时,它们并没有返回所有的html代码(我需要的部分)。
AHL网站:https://theahl.com/stats/daily-schedule/2021-2-7?league=4&season=68&division=-1当我按下inspect时,我在<div class = "ht-team-name" ... >下得到了球队名称,在<span class = "ht-period-value ht-total">下得到了比分。但是,当我运行以下两个代码示例时,这两行代码(加上更多行)消失了。不确定为什么会发生这种情况,任何解决方案都会很棒!
正在尝试请求(不起作用):
from bs4 import BeautifulSoup
import requests
url = "https://theahl.com/stats/daily-schedule/2021-2-7?league=4&season=68&division=-1"
headers = {"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.101 Safari/537.36"}
html = requests.get(url,headers=headers).content
soup = BeautifulSoup(html, 'html.parser')
team_name = soup.find_all('div',{'class':'ht-team-name'})
team_score = soup.find_all('span',{'class':'ht-period-value ht-total'})
#Prints list of team names but is empty list
print(team_name)
#Prints list of scores but is empty list
print(team_score)或者尝试使用phantomjs (对我来说,对其他一些不能处理请求的网站起作用了,但这也不起作用)
from bs4 import BeautifulSoup
from selenium import webdriver
url = "https://theahl.com/stats/daily-schedule/2021-2-7?league=4&season=68&division=-1"
browser = webdriver.PhantomJS('phantomjs/phantomjs.exe')
browser.get(url)
html = browser.page_source
soup = BeautifulSoup(html, 'html.parser')
team_name = soup.find_all('div',{'class':'ht-team-name'})
team_score = soup.find_all('span',{'class':'ht-period-value ht-total'})
#Prints list of team names but is empty list
print(team_name)
#Prints list of scores but is empty list
print(team_score)顺便说一下,如果您打印html而不是打印team_name和team_score,这两个类仍然不在代码中,所以我不认为这是我解析html的方式,但它可能会很有趣!
发布于 2021-07-14 04:53:49
requests不会有帮助,因为内容是通过javascript加载的。也许你只需要稍等片刻就可以加载内容了。
import time
from selenium import webdriver
url = "https://theahl.com/stats/daily-schedule/2021-2-7?league=4&season=68&division=-1"
browser = webdriver.Chrome()
browser.get(url)
time.sleep(10)
print(browser.find_elements_by_css_selector('div.ht-team-name'))
print(browser.find_elements_by_css_selector('span.ht-total.ht-period-value'))
browser.quit()上面的代码为两个选择器输出了几个匹配项。
time.sleep(...),因为我懒得使用waits。
顺便说一句,我没有PhantomJS,所以Chrome。
https://stackoverflow.com/questions/68369002
复制相似问题