Python库请求打开错误的页面

标签 python python-requests

我尝试使用 python requests 库打开一个 html 页面,但我的代码打开了站点根文件夹,我不明白如何解决问题。

import requests

scraping = requests.request("POST", url = "http://www.pollnet.it/WeeklyReport_it.aspx?ID=69")

print scraping.content

谢谢大家的建议!

最佳答案

您可以轻松看到服务器正在重定向到主页。

➜  ~  http -v http://www.pollnet.it/WeeklyReport_it.aspx\?ID\=69
GET /WeeklyReport_it.aspx?ID=69 HTTP/1.1
Accept: */*
Accept-Encoding: gzip, deflate
Connection: keep-alive
Host: www.pollnet.it
User-Agent: HTTPie/0.9.3



HTTP/1.1 302 Found
Content-Length: 131
Content-Type: text/html; charset=utf-8
Date: Sun, 07 Feb 2016 11:24:52 GMT
Location: /default.asp
Server: Microsoft-IIS/7.5
X-Powered-By: ASP.NET

<html><head><title>Object moved</title></head><body>
<h2>Object moved to <a href="%2fdefault.asp">here</a>.</h2>
</body></html>
<小时/>

进一步检查,可以看出Web服务器使用了 session cookie。

➜  ~  http -v http://www.pollnet.it/default_it.asp

HTTP/1.1 200 OK
Cache-Control: private
Content-Encoding: gzip
Content-Length: 9471
Content-Type: text/html; Charset=utf-8
Date: Sun, 07 Feb 2016 13:21:41 GMT
Server: Microsoft-IIS/7.5
Set-Cookie: ASPSESSIONIDSQTSTAST=PBHDLEIDFCNMPKIGANFDNMLK; path=/
Vary: Accept-Encoding
X-Powered-By: ASP.NET

这意味着每次访问主页时,服务器都会发送一个“Set-Cookie” header ,指示浏览器设置某些cookie。然后,每次浏览器请求每周报告时,服务器都会验证 session cookie。

通常情况下。 requests 包不会在请求之间保存 cookie,但是为了进行抓取,我们可以使用 Session 对象来在页面请求之间保存 cookie。

import requests

# create a Session object
s= requests.Session()

# first visit the main page
s.get("http://www.pollnet.it/default_it.asp")

# then we can visit the weekly report pages
r = s.get("http://www.pollnet.it/WeeklyReport_it.aspx?ID=69")

print(r.text)

# another page
r = s.get("http://www.pollnet.it/WeeklyReport_it.aspx?ID=89")
print(r.text)

但这里有一些建议 - Web 服务器可能只允许使用某个 Session 对象打开固定数量的页面(可能是 10 个,可能是 15 个)。要么立即验证 r.text 每次的结果(也许检查请求正文的长度以确保它不会太小),要么创建一个新的 Session 对象,每 5 或 6 页。

有关 session 对象的更多信息 here .

关于Python库请求打开错误的页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35252592/

相关文章:

Python compiler call another python compiler to execute a script(从一台独立机器到另一台机器执行脚本)

python - 网页抓取谷歌 - 得到不同的结果

python - 播放 WAV 歌曲时机器人不跳舞

python - h5py 中的组是否保留其成员添加的顺序?

不使用表单而只使用 Flask 作为 API 上传文件的 Python 脚本

python - 如何模拟使用 getattr 动态调用的请求方法

python 异步请求

Python POST 请求直到在谷歌应用引擎上等待超时时间后才发送请求

c++ - 将 Python 代码编译为 Pascal DLL

python - 从纬度/经度坐标计算像素值(使用 matplotlib basemap )