我尝试使用 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/