A. python http referer字段怎么用
HTTP Referer是header的一部分,当浏览器向web服务器发送请求的时候,一般会带上Referer,告诉服务器我是从哪个页面链接过来的,服务器籍此可以获得一些信息用于处理。用于统计访问量、防外连接等。
B. python 可以伪造 ip 发送 http 请求吗
有些 web 服务器校验客户端的真实 ip 是直接从 http headers 里边读,可以伪造 x-forward-for, x-real-ip 来欺骗 web 服务器,但是大部分都没办法通过这种办法来伪造。
C. python的httplib,urllib和urllib2的区别及用
宗述
首先来看一下他们的区别
urllib和urllib2
urllib 和urllib2都是接受URL请求的相关模块,但是urllib2可以接受一个Request类的实例来设置URL请求的headers,urllib仅可以接受URL。
这意味着,你不可以伪装你的User Agent字符串等。
urllib提供urlencode方法用来GET查询字符串的产生,而urllib2没有。这是为何urllib常和urllib2一起使用的原因。
目前的大部分http请求都是通过urllib2来访问的
httplib
httplib实现了HTTP和HTTPS的客户端协议,一般不直接使用,在更高层的封装模块中(urllib,urllib2)使用了它的http实现。
urllib简单用法
urllib.urlopen(url[, data[, proxies]]) :
[python] view plain
google = urllib.urlopen('')
print 'http header:/n', google.info()
print 'http status:', google.getcode()
print 'url:', google.geturl()
for line in google: # 就像在操作本地文件
print line,
google.close()
详细使用方法见
urllib学习
urllib2简单用法
最简单的形式
import urllib2
response=urllib2.urlopen(')
html=response.read()
实际步骤:
1、urllib2.Request()的功能是构造一个请求信息,返回的req就是一个构造好的请求
2、urllib2.urlopen()的功能是发送刚刚构造好的请求req,并返回一个文件类的对象response,包括了所有的返回信息。
3、通过response.read()可以读取到response里面的html,通过response.info()可以读到一些额外的信息。
如下:
#!/usr/bin/env python
import urllib2
req = urllib2.Request("")
response = urllib2.urlopen(req)
html = response.read()
print html
有时你会碰到,程序也对,但是服务器拒绝你的访问。这是为什么呢?问题出在请求中的头信息(header)。 有的服务端有洁癖,不喜欢程序来触摸它。这个时候你需要将你的程序伪装成浏览器来发出请求。请求的方式就包含在header中。
常见的情形:
import urllib
import urllib2
url = '
user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'# 将user_agent写入头信息
values = {'name' : 'who','password':'123456'}
headers = { 'User-Agent' : user_agent }
data = urllib.urlencode(values)
req = urllib2.Request(url, data, headers)
response = urllib2.urlopen(req)
the_page = response.read()
values是post数据
GET方法
例如网络:
,这样我们需要将{‘wd’:’xxx’}这个字典进行urlencode
#coding:utf-8
import urllib
import urllib2
url = ''
values = {'wd':'D_in'}
data = urllib.urlencode(values)
print data
url2 = url+'?'+data
response = urllib2.urlopen(url2)
the_page = response.read()
print the_page
POST方法
import urllib
import urllib2
url = ''
user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' //将user_agent写入头信息
values = {'name' : 'who','password':'123456'} //post数据
headers = { 'User-Agent' : user_agent }
data = urllib.urlencode(values) //对post数据进行url编码
req = urllib2.Request(url, data, headers)
response = urllib2.urlopen(req)
the_page = response.read()
urllib2带cookie的使用
#coding:utf-8
import urllib2,urllib
import cookielib
url = r''
#创建一个cj的cookie的容器
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
#将要POST出去的数据进行编码
data = urllib.urlencode({"email":email,"password":pass})
r = opener.open(url,data)
print cj
httplib简单用法
简单示例
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import httplib
import urllib
def sendhttp():
data = urllib.urlencode({'@number': 12524, '@type': 'issue', '@action': 'show'})
headers = {"Content-type": "application/x-www-form-urlencoded",
"Accept": "text/plain"}
conn = httplib.HTTPConnection('bugs.python.org')
conn.request('POST', '/', data, headers)
httpres = conn.getresponse()
print httpres.status
print httpres.reason
print httpres.read()
if __name__ == '__main__':
sendhttp()
具体用法见
httplib模块
python 3.x中urllib库和urilib2库合并成了urllib库。其中、
首先你导入模块由
import urllib
import urllib2
变成了
import urllib.request
然后是urllib2中的方法使用变成了如下
urllib2.urlopen()变成了urllib.request.urlopen()
urllib2.Request()变成了urllib.request.Request()
urllib2.URLError 变成了urllib.error.URLError
而当你想使用urllib 带数据的post请求时,
在python2中
urllib.urlencode(data)
而在python3中就变成了
urllib.parse.urlencode(data)
脚本使用举例:
python 2中
import urllib
import urllib2
import json
from config import settings
def url_request(self, action, url, **extra_data): abs_url = "http://%s:%s/%s" % (settings.configs['Server'],
settings.configs["ServerPort"],
url)
if action in ('get', 'GET'):
print(abs_url, extra_data)
try:
req = urllib2.Request(abs_url)
req_data = urllib2.urlopen(req, timeout=settings.configs['RequestTimeout'])
callback = req_data.read()
# print "-->server response:",callback
return callback
except urllib2.URLError as e:
exit("\033[31;1m%s\033[0m" % e)
elif action in ('post', 'POST'):
# print(abs_url,extra_data['params'])
try:
data_encode = urllib.urlencode(extra_data['params'])
req = urllib2.Request(url=abs_url, data=data_encode)
res_data = urllib2.urlopen(req, timeout=settings.configs['RequestTimeout'])
callback = res_data.read()
callback = json.loads(callback)
print("\033[31;1m[%s]:[%s]\033[0m response:\n%s" % (action, abs_url, callback))
return callback
except Exception as e:
print('---exec', e)
exit("\033[31;1m%s\033[0m" % e)
python3.x中
import urllib.request
import json
from config import settings
def url_request(self, action, url, **extra_data):
abs_url = 'http://%s:%s/%s/' % (settings.configs['ServerIp'], settings.configs['ServerPort'], url)
if action in ('get', 'Get'): # get请求
print(action, extra_data)try:
req = urllib.request.Request(abs_url)
req_data = urllib.request.urlopen(req, timeout=settings.configs['RequestTimeout'])
callback = req_data.read()
return callback
except urllib.error.URLError as e:
exit("\033[31;1m%s\033[0m" % e)
elif action in ('post', 'POST'): # post数据到服务器端
try:
data_encode = urllib.parse.urlencode(extra_data['params'])
req = urllib.request.Request(url=abs_url, data=data_encode)
req_data = urllib.request.urlopen(req, timeout=settings.configs['RequestTimeout'])
callback = req_data.read()
callback = json.loads(callback.decode())
return callback
except urllib.request.URLError as e:
print('---exec', e)
exit("\033[31;1m%s\033[0m" % e)
settings配置如下:
configs = {
'HostID': 2,
"Server": "localhost",
"ServerPort": 8000,
"urls": {
'get_configs': ['api/client/config', 'get'], #acquire all the services will be monitored
'service_report': ['api/client/service/report/', 'post'],
},
'RequestTimeout': 30,
'ConfigUpdateInterval': 300, # 5 mins as default
}
D. 使用python的requests库运行http请求,请问如图的报错是什么原因,要怎么解决的
post的参数顺序再检查确认一下,可以使用类似data=data,header=head的方式赋值避免混淆。
E. python3.6.1 的请求头里的横杠前后自动大写怎么办
http header fields 是 case insensitive 的,所以 Python 把你的 header 变成任何大小写都是正确的,并且你也不应该依赖于 header field 的大小写。
标准没有说过哪种形式更好,不过 common sense 是横杠间隔的大写开头单词。
F. 怎么知道python发送了什么http请求
本文实例讲述了python通过get,post方式发送http请求和接收http响应的方法。分享给大家供大家参考。具体如下:
测试用CGI,名字为test.py,放在apache的cgi-bin目录下:
#!/usr/bin/python
import cgi
def main():
print "Content-type: text/html\n"
form = cgi.FieldStorage()
if form.has_key("ServiceCode") and form["ServiceCode"].value != "":
print "<h1> Hello",form["ServiceCode"].value,"</h1>"
else:
print "<h1> Error! Please enter first name.</h1>"
main()
python发送post和get请求
get请求:
使用get方式时,请求数据直接放在url中。
方法一、
import urllib
import urllib2
url = "test.py?ServiceCode=aaaa"
req = urllib2.Request(url)
print req
res_data = urllib2.urlopen(req)
res = res_data.read()
print res
方法二、
import httplib
url = "hest/test.py?ServiceCode=aaaa"
conn = httplib.HTTPConnection("192.168.81.16")
conn.request(method="GET",url=url)
response = conn.getresponse()
res= response.read()
print res
post请求:
使用post方式时,数据放在data或者body中,不能放在url中,放在url中将被忽略。
方法一、
import urllib
import urllib2
test_data = {'ServiceCode':'aaaa','b':'bbbbb'}
test_data_urlencode = urllib.urlencode(test_data)
requrl = "/python_test/test.py"
req = urllib2.Request(url = requrl,data =test_data_urlencode)
print req
res_data = urllib2.urlopen(req)
res = res_data.read()
print res
方法二、
import urllib
import httplib
test_data = {'ServiceCode':'aaaa','b':'bbbbb'}
test_data_urlencode = urllib.urlencode(test_data)
requrl = "python_test/test.py"
headerdata = {"Host":"116"}
conn = httplib.HTTPConnection("192.168.81.16")
conn.request(method="POST",url=requrl,body=test_data_urlencode,headers = headerdata)
response = conn.getresponse()
res= response.read()
print res
对python中json的使用不清楚,所以临时使用了urllib.urlencode(test_data)方法;
模块urllib,urllib2,httplib的区别
httplib实现了http和https的客户端协议,但是在python中,模块urllib和urllib2对httplib进行了更上层的封装。
介绍下例子中用到的函数:
1、HTTPConnection函数
httplib.HTTPConnection(host[,port[,stict[,timeout]]])
这个是构造函数,表示一次与服务器之间的交互,即请求/响应
host 标识服务器主机(服务器IP或域名)
port 默认值是80
strict 模式是False,表示无法解析服务器返回的状态行时,是否抛出BadStatusLine异常
例如:
conn = httplib.HTTPConnection("1.16",80) 与服务器建立链接。
2、HTTPConnection.request(method,url[,body[,header]])函数
这个是向服务器发送请求
method 请求的方式,一般是post或者get,
例如:
method="POST"或method="Get"
url 请求的资源,请求的资源(页面或者CGI,我们这里是CGI)
例如:
url="htti-bin/python_test/test.py" 请求CGI
或者
url="ht_test/test.html" 请求页面
body 需要提交到服务器的数据,可以用json,也可以用上面的格式,json需要调用json模块
headers 请求的http头headerdata = {"Host":"192.168.81.16"}
例如:
test_data = {'ServiceCode':'aaaa','b':'bbbbb'}
test_data_urlencode = urllib.urlencode(test_data)
requrl = "hgi-bin/python_test/test.py"
headerdata = {"Host":"192.116"}
conn = httplib.HTTPConnection("196",80)
conn.request(method="POST",url=requrl,body=test_data_urlencode,headers = headerdata)
conn在使用完毕后,应该关闭,conn.close()
3、HTTPConnection.getresponse()函数
这个是获取http响应,返回的对象是HTTPResponse的实例。
4、HTTPResponse介绍:
HTTPResponse的属性如下:
read([amt]) 获取响应消息体,amt表示从响应流中读取指定字节的数据,没有指定时,将全部数据读出;
getheader(name[,default]) 获得响应的header,name是表示头域名,在没有头域名的时候,default用来指定返回值
getheaders() 以列表的形式获得header
例如:
date=response.getheader('date');
print date
resheader=''
resheader=response.getheaders();
print resheader
列形式的响应头部信息:
[('content-length', '295'), ('accept-ranges', 'bytes'), ('server', 'Apache'), ('last-modified', 'Sat, 31 Mar 2012 10:07:02 GMT'), ('connection', 'close'), ('etag', '"e8744-127-4bc871e4fdd80"'), ('date', 'Mon, 03 Sep 2012 10:01:47 GMT'), ('content-type', 'text/html')]
date=response.getheader('date');
print date
取出响应头部的date的值。
G. 一下python代码中的headers是什么意思,怎么理解
headers参数指定HTTP请求附件头部信息,有时候附件的头信息确实没有影响,因为服务器为了增加包容性,会尽可能使得更加广泛的情形都正常工作。
H. python爬虫 如何解决http error 503问题
从表面上看,Python爬虫程序运行中出现503错误是服务器的问题,其实真正的原因在程序,由于Python脚本运行过程中读取的速度太快,明显是自动读取而不是人工查询读取,这时服务器为了节省资源就会给Python脚本反馈回503错误。其实只要把爬取的速度放慢一点就好了。比如读取一条记录或几条记录后适当添加上time.sleep(10),这样就基本上不会出现503错误了。我本人在使用中一般是在每一次读取后都运行time.sleep(1)或time.sleep(3),具体的数值根据不同的网站确定。
I. 如何用Python写一个http post请求
HTTP 协议规定 POST 提交的数据必须放在消息主体(entity-body)中,但协议并没有规定数据必须使用什么编码方式。常见的四种编码方式如下:
1、application/x-www-form-urlencoded
这应该是最常见的 POST 提交数据的方式了。浏览器的原生 form 表单,如果不设置 enctype 属性,那么最终就会以 application/x-www-form-urlencoded 方式提交数据。请求类似于下面这样(无关的请求头在本文中都省略掉了):
POST HTTP/1.1 Content-Type:
application/x-www-form-urlencoded;charset=utf-8
title=test&sub%5B%5D=1&sub%5B%5D=2&sub%5B%5D=3
2、multipart/form-data
这又是一个常见的 POST 数据提交的方式。我们使用表单上传文件时,必须让 form 的 enctyped 等于这个值,下面是示例
POST HTTP/1.1
Content-Type:multipart/form-data; boundary=----
------
Content-Disposition: form-data; name="text"
title
------
Content-Disposition: form-data; name="file"; filename="chrome.png"
Content-Type: image/png
PNG ... content of chrome.png ...
--------
3、application/json
application/json 这个 Content-Type 作为响应头大家肯定不陌生。实际上,现在越来越多的人把它作为请求头,用来告诉服务端消息主体是序列化后的 JSON 字符串。由于 JSON 规范的流行,除了低版本 IE 之外的各大浏览器都原生支持 JSON.stringify,服务端语言也都有处理 JSON 的函数,使用 JSON 不会遇上什么麻烦。
4、text/xml
它是一种使用 HTTP 作为传输协议,XML 作为编码方式的远程调用规范。
那么Python在调用外部http请求时,post请求怎么传请求体呢?说实话楼主只实践过【1、application/x-www-form-urlencoded】【2、multipart/form-data 】和【3、application/json】
一、application/x-www-form-urlencoded
import urllib
url = ""
body_value = {"package": "com.tencent.lian","version_code": "66" }
body_value = urllib.urlencode(body_value)
request = urllib2.Request(url, body_value)
request.add_header(keys, headers[keys])
result = urllib2.urlopen(request ).read()
二、multipart/form-data
需要利用python的poster模块,安装poster:pip install poster
代码:
from poster.encode import multipart_encode
from poster.streaminghttp import register_openers
url = ""
body_value = {"package": "com.tencent.lian","version_code": "66" }
register_openers()
datagen, re_headers = multipart_encode(body_value)
request = urllib2.Request(url, datagen, re_headers)
# 如果有请求头数据,则添加请求头
request .add_header(keys, headers[keys])
result = urllib2.urlopen(request ).read()
二、application/json
import json
url = ""
body_value = {"package": "com.tencent.lian","version_code": "66" }
register_openers()
body_value = json.JSONEncoder().encode(body_value)
request = urllib2.Request(url, body_value)
request .add_header(keys, headers[keys])
result = urllib2.urlopen(request ).read()