Fro*_*tyX 5 python cookies screen-scraping beautifulsoup
我正在尝试抓取当天所有足球(足球)比赛的以下网址: https: //www.soccerstats.com/matches.asp ?matchday=2&daym=tomorrow
我的代码曾经有效,但网站后来发生了变化,您现在需要在网站加载页面之前单击“我同意 cookie”按钮。这现在导致我的代码出现问题。对此有什么解决办法吗?
任何帮助深表感谢。
我尝试查看 bs4 的文本输出,很明显该网站尚未加载,而是在输出中看到“我同意 cookies”文本,这意味着它没有通过此阶段。
from bs4 import BeautifulSoup
import requests
url = "https://www.soccerstats.com/matches.asp?matchday=2"
r = requests.get(url)
data = r.text
soup = BeautifulSoup(data, 'html.parser')
all_matches = []
all_matches = re.findall(r"""<a class='button' style='background-color:#AAAAAA;font-color=white;' href='(.*?)'>""", data)
Run Code Online (Sandbox Code Playgroud)
输出应列出各个匹配 URL。
当您点击“我同意 cookie”时,网站会向您的浏览器发送一个 cookie,基本上告诉网站“该用户已同意 cookie”。您可以在 Chrome 的 DevTools 之类的工具中捕获此 cookie,方法是打开“应用程序”选项卡并单击左侧的“Cookie”,然后导航到您所在的网站。
完成此操作后,单击“我同意 cookie”并查看添加到您的浏览器中的 cookie。在我正在查看的网站上,添加的 cookie 之一的调用__hs_opt_out值为no。然后,您可以简单地将该 cookie 添加到您的请求中:
r = requests.get(url, cookies={'__hs_opt_out': 'no'})
Run Code Online (Sandbox Code Playgroud)
或者,甚至更好:
s = requests.Session()
s.cookies.update({'__hs_opt_out': 'no'})
s.get(url) # Automatically uses the session cookies
# Some more code...
s.get(other_url) # Remembers the cookie from before
Run Code Online (Sandbox Code Playgroud)