python3中,使用get提交表单时怎样使用header

python3中,使用get提交表单时怎样使用header,第1张

def openUrl(url):

    import urllib2

    url = 'http://' + url

    req = urllib2.Request(url)

    //根据你自己的需要设置header,add_header方法中需要两个参数,key和value的键值对

    req.add_header('User-agent', 'Mozilla/5.0 (Windows NT 6.2 WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1707.0 Safari/537.36')

    response = urllib2.urlopen(req)

    the_page = response.read()

    print the_page

    print response.geturl()

    print response.info()

    print response.headers

openUrl('xxx.xxx.xxx')

1、urllib2可以接受一个Request类的实例来设置URL请求的headers,urllib仅可以接受URL。这意味着,你不可以通过urllib模块伪装你的User Agent字符串等(伪装浏览器)。

2、urllib提供urlencode方法用来GET查询字符串的产生,而urllib2没有。这是为何urllib常和urllib2一起使用的原因。

3、urllib2模块比较优势的地方是urlliburllib2.urlopen可以接受Request对象作为参数,从而可以控制HTTP Request的header部。

4、但是urllib.urlretrieve函数以及urllib.quote等一系列quote和unquote功能没有被加入urllib2中,因此有时也需要urllib的辅助。

#需要使用urllib2模块

import urllib2

#post的数据

url = ''

data = {

    "ie": "",

    "kw": "",

}

#post头部

headers = {

    "Host": "",

    "User-Agent": "",

    "Cookie": ""

}

request = urllib2.Request(url, data, headers)

response = urllib2.urlopen(request)

data = response.read()


欢迎分享,转载请注明来源:内存溢出

原文地址: http://www.outofmemory.cn/bake/11708807.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-18
下一篇 2023-05-18

发表评论

登录后才能评论

评论列表(0条)

保存