如何在此脚本上添加useragent:
#!/usr/bin/python
import httplib
saudidos = True
while saudidos:
conn = httplib.HTTPConnection("127.0.0.1")
conn.request("GET", "/");
答案 0 :(得分:1)
有点迟到的回复,但我想为可能找到此页面的任何人添加上一个回复。简短的回答是使用HTTPConnection
实例的请求方法。它应该被声明为字典。这是一个比上面更简洁的例子:
headers = {'foo': 'bar'}
connection = httplib.HTTPConnection('hostname')
connection.request('GET', headers)
您还可以添加以下内容以更详细地查看您的回复:
response = connection.getresponse()
print response.status, response.reason # this is python 2 syntax
data = response.read()
print data
我建议您使用https://requestb.in/查看您发送的内容!
答案 1 :(得分:0)
这里有示例如何发送标题:
Example: Using the httplib module to post data
# File: httplib-example-2.py
import httplib
USER_AGENT = "httplib-example-2.py"
def post(host, path, data, type=None):
http = httplib.HTTP(host)
# write header
http.putrequest("PUT", path)
http.putheader("User-Agent", USER_AGENT)
http.putheader("Host", host)
if type:
http.putheader("Content-Type", type)
http.putheader("Content-Length", str(len(data)))
http.endheaders()
# write body
http.send(data)
# get response
errcode, errmsg, headers = http.getreply()
if errcode != 200:
raise Error(errcode, errmsg, headers)
file = http.getfile()
return file.read()
if __name__ == "__main__":
post("www.spam.egg", "/bacon.htm", "a piece of data", "text/plain")
答案 2 :(得分:0)
如果您使用的是httplib2,则应使用标头dict以与请求模块相同的方式执行请求:
from httplib2 import Http
http = Http()
headers = {"user-agent": "Mozilla/5.0"}
url = "https://www.google.com"
_, content = http.request(url, "GET", headers=headers)