【发布时间】:2012-10-05 17:53:19
【问题描述】:
我爬过很多网站,经常想知道为什么 Firebug 中显示的响应标头和 urllib.urlopen(url).info() 返回的响应标头通常不同,因为 Firebug 报告了 MORE 标头。
我今天遇到了一个有趣的人。我通过在重定向到最终页面之前完全加载(返回 200 状态代码)的“搜索 url”来抓取网站。执行抓取的最简单方法是返回 Location 响应标头并发出另一个请求。但是,当我运行 'urllib.urlopen(url).info().
这里有区别:
Firebug 标头:
Cache-Control : no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Connection : keep-alive
Content-Encoding : gzip
Content-Length : 2433
Content-Type : text/html
Date : Fri, 05 Oct 2012 15:59:31 GMT
Expires : Thu, 19 Nov 1981 08:52:00 GMT
Location : /catalog/display/1292/index.html
Pragma : no-cache
Server : Apache/2.0.55
Set-Cookie : PHPSESSID=9b99dd9a4afb0ef0ca267b853265b540; path=/
Vary : Accept-Encoding,User-Agent
X-Powered-By : PHP/4.4.0
我的代码返回的标题:
Date: Fri, 05 Oct 2012 17:16:23 GMT
Server: Apache/2.0.55
X-Powered-By: PHP/4.4.0
Set-Cookie: PHPSESSID=39ccc547fc407daab21d3c83451d9a04; path=/
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Vary: Accept-Encoding,User-Agent
Content-Type: text/html
Connection: close
这是我的代码:
from BeautifulSoup import BeautifulSoup
import urllib
import psycopg2
import psycopg2.extras
import scrape_tools
tools = scrape_tools.tool_box()
db = tools.db_connect()
cursor = db.cursor(cursor_factory = psycopg2.extras.RealDictCursor)
cursor.execute("SELECT data FROM table WHERE variable = 'Constant' ORDER BY data")
for row in cursor:
url = 'http://www.website.com/search/' + row['data']
headers = {
'Accept' : 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Encoding' : 'gzip, deflate',
'Accept-Language' : 'en-us,en;q=0.5',
'Connection' : 'keep-alive',
'Host' : 'www.website.com',
'User-Agent' : 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:15.0) Gecko/20100101 Firefox/15.0.1'
}
post_params = {
'query' : row['data'],
'searchtype' : 'products'
}
post_args = urllib.urlencode(post_params)
soup = tools.request(url, post_args, headers)
print tools.get_headers(url, post_args, headers)
请注意:scrape_tools 是我自己编写的模块。模块中包含的用于检索标头的代码(基本上)如下:
class tool_box:
def get_headers(self, url, post, headers):
file_pointer = urllib.urlopen(url, post, headers)
return file_pointer.info()
有差异的原因吗?我在我的代码中犯了一个愚蠢的错误吗?如何检索丢失的标头数据?我对 Python 还很陌生,所以请原谅任何愚蠢的错误。
提前致谢。非常感谢任何建议!
还有...对不起代码墙=\
【问题讨论】:
-
BS 用于解析 HTML/XML,而不是 HTTP 标头。
-
我的目标不是用 BS 解析 HTTP 标头。我的问题是如何检索标题以继续我的抓取和解析 HTML...
-
这两个响应的状态码是什么?
-
我刚刚注意到您已经观察到重定向并提到了它,即使我多次阅读了这个问题,我也不知何故错过了 :)
标签: python http-headers urllib