使用Python requests登录网站并下载文件

4
我有一个带有HTML表单的网站。登录后,它会带我到一个start.php页面,然后重定向到一个overview.php页面。
我想从那个服务器上下载文件... 当我点击一个ZIP文件的下载链接时,链接后面的地址是:
getimage.php?path="vol/img"&id="4312432"

如何使用requests实现这个功能?我尝试创建一个会话并使用正确的参数进行GET请求...但是得到的答复只是未登录时看到的网站页面。
c = requests.Session()
c.auth =('myusername', 'myPass')
request1 = c.get(myUrlToStart.PHP)
tex = request1.text

with open('data.zip', 'wb') as handle:
    request2 = c.get(urlToGetImage.Php, params=payload2, stream=True)
    print(request2.headers)
    for block in request2.iter_content(1024):
        if not block:
            break

        handle.write(block)
2个回答

3
您正在使用基本身份验证进行请求。这不会填写显示在页面上的表单。
如果您知道您的表单发送POST请求的URL,那么您可以尝试将表单数据直接发送到该URL。

如果他们不知道它,那么很可能可以从表单所在页面的HTML中获取。 - bdeniker
我知道URL,我试图发送有效载荷:
来自HTML的表单数据: '<form action="../startup.php" method="post">'
Python有效载荷: payload = { 'action': 'login', 'username': 'user', 'password': 'Pass' }
使用requests.Session()对象c发送请求 request1 = c.post(url1, data=payload)
但是当我尝试输出print(request1.text)时,我只得到了登录表单。
- hmrc87
你的负载字典中可能不需要键“action”。也许页面上有隐藏的输入字段也是必需的?查看HTML表单的源代码(可能会自动生成CSRF保护值,在这种情况下,您将不得不填写表单,然后提交它)。 - Johannes Charra
我尝试打印request1.url,结果给出了以下信息:Your%20Userid%20is%20currently%20logged%20in.%3Cbr%20/%3EIf%20you%20feel%20this%20message%20is%20an%20error%20contact%20your%20system%20administrator. - hmrc87

3
寻找相同东西的人可以尝试这个...
import requests
import bs4

site_url = 'site_url_here'
userid = 'userid'
password = 'password'

file_url = 'getimage.php?path="vol/img"&id="4312432"' 
o_file = 'abc.zip'  

# create session
s = requests.Session()
# GET request. This will generate cookie for you
s.get(site_url)
# login to site.
s.post(site_url, data={'_username': userid, '_password': password})
# Next thing will be to visit URL for file you would like to download.
r = s.get(file_url)

# Download file
with open(o_file, 'wb') as output:
    output.write(r.content)
print(f"requests:: File {o_file} downloaded successfully!")

# Close session once all work done
s.close()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接