【问题标题】:Web Scraping using Requests - Python使用请求进行 Web 抓取 - Python
【发布时间】:2023-03-23 05:30:01
【问题描述】:

我正在尝试使用 Resquest 库获取数据,但我做错了。我的解释,手动搜索:

网址 - https://www9.sabesp.com.br/agenciavirtual/pages/template/siteexterno.iface?idFuncao=18

我填写“Informe o RGI”字段,然后单击 Prosseguir 按钮(如下一步):

enter image description here

我得到这个结果:

enter image description here

在编码之前,我进行了手动搜索并检查了表单数据:

enter image description here

然后我用这段代码试了一下:

import requests

data = { "frmhome:rgi1": "0963489410"}

url = "https://www9.sabesp.com.br/agenciavirtual/block/send-receive-updates"
res = requests.post(url, data=data)

print(res.text)

我的输出是:

<session-expired/>

我做错了什么?

非常感谢。

【问题讨论】:

    标签: python web-scraping python-requests python-requests-html


    【解决方案1】:

    当您使用浏览器访问该站点时,会创建一个会话并将其存储在您计算机上的 cookie 中。当您发出 POST 请求时,cookie 会随请求一起发送。您收到 session-expired 错误,因为您没有随请求发送任何会话数据。

    试试这个代码。它首先请求入口页面并存储 cookie。然后 cookie 与 POST 请求一起发送。

    import requests
    
    session = requests.Session() # start session
    
    # get entry page with cookies
    response = session.get('https://www9.sabesp.com.br/agenciavirtual/pages/home/paginainicial.iface', timeout=30)
    cks = session.cookies  # save cookies with Session data
    print(session.cookies.get_dict())
    
    data = { "frmhome:rgi1": "0963489410"}
    
    url = "https://www9.sabesp.com.br/agenciavirtual/block/send-receive-updates"
    res = requests.post(url, data=data, cookies=cks)  # send cookies with request
    
    print(res.text)
    

    【讨论】:

    • 嗨@Mike67。谢谢你。不幸的是,退货是空的。你知道为什么会这样吗?我真正需要的是通过Form搜索后的HTML响应页面。
    • 我在 Chrome 中使用 devtools 查看了请求。看起来按钮发送了大约 30 个字段。我不知道需要哪些字段才能获得回复。
    • 我也去过那里,但没有找到任何我想要的东西。没关系。我真的很感激。
    猜你喜欢
    • 1970-01-01
    • 2018-06-23
    • 1970-01-01
    • 2018-10-19
    • 1970-01-01
    • 2017-05-21
    • 1970-01-01
    • 1970-01-01
    • 2021-06-29
    相关资源
    最近更新 更多