【问题标题】:Web scraping after authentication using requests使用请求进行身份验证后的 Web 抓取
【发布时间】:2021-01-11 11:09:50
【问题描述】:

我在 Python 3.9 中做一个网页抓取脚本。

我想从这个网站收集一些信息:https://www.matchendirect.fr/。 这个网站是法语的,但我不认为试图帮助我是一个真正的问题。

我需要的信息是鼠标悬停在“Pronostics des internautes”部分中显示的数组。 HTML 代码以:<table class="table table-bordered MEDtpro">

开头

我已经在浏览器上重新创建了 cookie,以按照本文How to send cookies with urllib 上的答案模拟我的连接,但它不起作用。

这是我的代码:

#!/usr/bin/python3
# -*- coding: utf-8 -*-
import requests

cookies = {
    'PHPSESSID': 'a2q4evve875s1ibamiqmc93ru6',
    'c_compte_cle': '76598fbd4fe763e768dc79275c02e11f',
    'c_compte_id':'311084',
    'c_compte_pseudo':'foobar',
    'c_compte_url_image':'%2Fimage%2Fcommun%2Fmembre-med-t16.png',
    'c_coucours_promo':'3'
    }
headers = {'User-Agent': 'Mozilla/5.0'}


link = "https://www.matchendirect.fr/live-score/caen-toulouse.html"

response = requests.get(link, cookies=cookies, headers=headers)
webpage = response.text

print("Success!") if webpage.find('<table class="table table-bordered MEDtpro">')>-1 else print("Failed!")

有人可以帮我解决这个问题吗?

此帐户是一个垃圾帐户,供想要测试的人使用。

【问题讨论】:

  • 您是否在登录后尝试解析 HTML?
  • 据我所见,登录弹出页面没有使用标准登录 - 即使 POSTs 到 https://www.matchendirect.fr/cgi/ajax/authentification_action.php?f_contexte=classique,表单数据也不存在。因此,页面上的 Javascript 可能会在 POST 之前修改输入数据。您可能需要使用Selenium 与页面交互或抓取它。无论如何,既然您使用的是requests,请继续阅读Sessions。也许你没有设置足够的 cookie。
  • 感谢您帮助我。我已编辑帖子以删除有关帐户名和密码的信息。顺便说一句,我会删除帐户。

标签: python python-3.x web-scraping python-requests


【解决方案1】:

您要查找的内容由AJAX 请求更新。您可以通过将请求发送到AJAX URL 来查找数据。

#!/usr/bin/python3
# -*- coding: utf-8 -*-
import requests
from bs4 import BeautifulSoup


link = "https://www.matchendirect.fr/live-score/caen-toulouse.html"

response = requests.get(link)
soup = BeautifulSoup(response.content, "html.parser")
f_id_match = soup.find("input", {"name": "f_pronostic_id_match"})["value"]


data_response = requests.get("https://www.matchendirect.fr/cgi/ajax/liste_pronostic.php?f_id_match={}&f_id_grille=".format(f_id_match))
webpage = data_response.text


print("Success!") if webpage.find('<table class="table table-bordered MEDtpro">')>-1 else print("Failed!")

您需要从页面中找到f_id_match,然后向该AJAX 网址发送新请求以查找您要查找的内容。

不要设置 cookie 来模拟浏览器,使用 requests.Session() 创建类似浏览器的会话,然后尝试浏览 URL

【讨论】:

  • 谢谢你的回答,我试试看。
  • 如果它解决了您的问题,请考虑接受它作为答案。
  • 非常感谢,一切正常。您在 data_response.format 中输入了一个小错误,{} 之间缺少 0。
猜你喜欢
  • 1970-01-01
  • 2015-12-04
  • 1970-01-01
  • 2014-10-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-10
  • 2022-06-12
相关资源
最近更新 更多