我正在使用Python Requests模块来进行网站数据挖掘。在数据挖掘的过程中,我需要HTTP POST一个表单,并通过检查生成的URL来检查是否成功。我的问题是,在POST之后,是否有可能请求服务器不发送整个页面?我只需要检查URL,但是我的程序下载了整个页面并消耗了不必要的带宽。代码非常简单。
import requests
r = requests.post(URL, payload)
if 'keyword' in r.url:
success
fail
我正在使用Python Requests模块来进行网站数据挖掘。在数据挖掘的过程中,我需要HTTP POST一个表单,并通过检查生成的URL来检查是否成功。我的问题是,在POST之后,是否有可能请求服务器不发送整个页面?我只需要检查URL,但是我的程序下载了整个页面并消耗了不必要的带宽。代码非常简单。
import requests
r = requests.post(URL, payload)
if 'keyword' in r.url:
success
fail
如果你能实现,一种简单的解决方案是采用低级别的方式。使用Socket库。 例如,你需要发送一个带有数据的POST请求。我在我的爬虫程序中就使用了这种方法。
import socket
from urllib import quote # POST body is escaped. use quote
req_header = "POST /{0} HTTP/1.1\r\nHost: www.yourtarget.com\r\nUser-Agent: For the lulz..\r\nContent-Type: application/x-www-form-urlencoded; charset=UTF-8\r\nContent-Length: {1}"
req_body = quote("data1=yourtestdata&data2=foo&data3=bar=")
req_url = "test.php"
header = req_header.format(req_url,str(len(req_body))) #plug in req_url as {0}
#and length of req_body as Content-length
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) #create a socket
s.connect(("www.yourtarget.com",80)) #connect it
s.send(header+"\r\n\r\n"+body+"\r\n\r\n") # send header+ two times CR_LF + body + 2 times CR_LF to complete the request
page = ""
while True:
buf = s.recv(1024) #receive first 1024 bytes(in UTF-8 chars), this should be enought to receive the header in one try
if not buf:
break
if "\r\n\r\n" in page: # if we received the whole header(ending with 2x CRLF) break
break
page+=buf
s.close() # close the socket here. which should close the TCP connection even if data is still flowing in
# this should leave you with a header where you should find a 302 redirected and then your target URL in "Location:" header statement.
如果您提供一些更多的数据,例如您正在尝试请求的示例URL,那将会很有帮助。话虽如此,我认为您通常是在使用以下算法依赖重定向或HTTP 404错误来检查您的POST请求后是否具有正确的URL:
if original_url == returned request url:
correct url to a correctly made request
else:
wrong url and a wrongly made request
requests
库中使用HTTP HEAD请求(另一种HTTP请求类型,如GET、POST等)来仅获取标头而不是页面正文。然后,您将检查响应代码和重定向URL(如果存在)以查看是否向有效的URL发出了请求。def attempt_url(url):
'''Checks the url to see if it is valid, or returns a redirect or error.
Returns True if valid, False otherwise.'''
r = requests.head(url)
if r.status_code == 200:
return True
elif r.status_code in (301, 302):
if r.headers['location'] == url:
return True
else:
return False
elif r.status_code == 404:
return False
else:
raise Exception, "A status code we haven't prepared for has arisen!"
如果这不完全符合您的要求,提供更多详细信息将会有所帮助。至少,这可以让您获取状态码和标头,而无需拉取所有页面数据。
HEAD
在这里没有帮助,因为要求发送表单数据,这需要发送 POST
。 - Piotr Dobrogost这个网站可能使用Post/Redirect/Get (PRG)模式。如果是这样,那么只需不跟随重定向并从响应中读取Location
头即可。
示例
>>> import requests
>>> response = requests.get('http://httpbin.org/redirect/1', allow_redirects=False)
>>> response.status_code
302
>>> response.headers['location']
'http://httpbin.org/get'
>>> import requests
>>> response = requests.get('http://httpbin.org/redirect/1', allow_redirects=False)
>>> response.status_code
302
>>> response.headers['location']
'http://httpbin.org/get'
>>> response2 = requests.head(response.headers['location'])
>>> response2.status_code
200
>>> response2.headers
{'date': 'Wed, 07 Nov 2012 20:04:16 GMT', 'content-length': '352', 'content-type':
'application/json', 'connection': 'keep-alive', 'server': 'gunicorn/0.13.4'}
prefetch=False
以避免立即下载正文。服务器可能在发布后重定向您。检查r.history
,看看requests
是否像浏览器一样在POST之后执行GET。还有一个redirect
参数,但我不知道它对于POST请求有什么作用。 - jfshttplib
的示例:http://ideone.com/KEQajG - jfs