gpt4 book ai didi

python - 使用Python通过下拉菜单+按钮进行抓取

转载 作者:行者123 更新时间:2023-12-01 01:03:18 26 4
gpt4 key购买 nike

我正在尝试从墨西哥中央银行网站上抓取数据,但遇到了困难。就操作而言,我需要首先访问初始 URL 中的链接。访问链接后,我需要选择 2 个下拉值,然后点击激活提交按钮。如果一切顺利,我将被带到一个新的 URL,其中提供了一组 pdf 链接。

原网址为:

"http://www.banxico.org.mx/mercados/valores-gubernamentales-secto.html "

嵌套 URL(带有保管箱的 URL)是:“http://www.banxico.org.mx/valores/LeePeriodoSectorizacionValores.faces?BMXC_claseIns=GUB&BMXC_lang=es_MX

输入(任意)为:“07/03/2019”和“14/03/2019”。

使用 BeautifulSoup 和请求,我觉得我已经填充了 dropbox 中的值,但未能单击按钮并通过链接列表获得最终 url。

我的代码如下:

from bs4 import BeautifulSoup
import requests

pagem=requests.get("http://www.banxico.org.mx/mercados/valores-gubernamentales-secto.html")
soupm = BeautifulSoup(pagem.content,"lxml")
lst=soupm.find_all('a', href=True)
url=lst[-1]['href']
page = requests.get(url)
soup = BeautifulSoup(page.content,"lxml")
xin= soup.find("select",{"id":"_id0:selectOneFechaIni"})
xfn= soup.find("select",{"id":"_id0:selectOneFechaFin"})
ino=list(xin.stripped_strings)
fino=list(xfn.stripped_strings)
headers = {'Referer': url}
data = {'_id0:selectOneFechaIni':'07/03/2019', '_id0:selectOneFechaFin':'14/03/2019',"_id0:accion":"_id0:accion"}
respo=requests.post(url,data,headers=headers)
print(respo.url)

在代码中,respo.url 等于 url...代码失败。有人可以帮我确定问题出在哪里吗?我是抓取新手,所以这可能是显而易见的 - 提前为此道歉......我将不胜感激任何帮助。谢谢!

最佳答案

上次我检查过,您无法通过使用 BeautifulSoup 和 Python 单击按钮来提交表单。我经常看到的通常有两种方法:

  1. 对表单进行逆向工程

如果表单进行 AJAX 调用(例如,在后台发出请求,这对于用 React 或 Angular 编写的 SPA 很常见),那么最好的方法是使用 Chrome 或其他浏览器中的网络请求选项卡来了解端点是什么以及有效负载是什么。获得这些答案后,您可以使用 requests 库通过 data=your_payload_dictionary 向该端点发出 POST 请求(例如,手动执行表单在幕后执行的操作) 。阅读 this post以获得更详细的教程。

  • 使用 headless 浏览器
  • 如果网站是用 ASP.NET 或类似的 MVC 框架编写的,那么最好的方法是使用 headless 浏览器填写表单并单击提交。一个流行的框架是 Selenium 。这模拟了一个普通的浏览器。阅读 this post以获得更详细的教程。

    通过粗略地查看您正在处理的页面来判断,我推荐方法#2。

    关于python - 使用Python通过下拉菜单+按钮进行抓取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55600958/

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