python3 get/post/自定义header/使用代理

一、get请求

get请求就是在构造Request对象时,只传入url参数

更多的教程发送get请求的写法直接是不构造Request对象而直接urllib.request.urlopen(url),但为了与后边post和header的统一推荐还是构造Request。

import urllib.request

url_request="http://10.10.6.92/Pages/login.htm"

request_obj=urllib.request.Request(url=url_request) response_obj
=urllib.request.urlopen(request_obj) html_code=response_obj.read().decode('utf-8') print(html_code)

二、post请求

post请求与get的区别,是在构造Request对象时除了传入url参数还要传入data参数

不用怀疑,真的加上data,发送数据时就自动由get方法改为post方法

import urllib.request

url_request="http://10.10.6.92/Pages/login.htm"
post_data='<?xml version="1.0" encoding="utf-8" ?><request version="1.0" systemType="NVMS-9000" clientType="WEB"><content><userName><![CDATA[admin]]></userName><password>MTIzNDU2</password></content></request>'
post_data=post_data.encode('utf-8')

request_obj=urllib.request.Request(url=url_request,data=post_data)
response_obj=urllib.request.urlopen(request_obj)
html_code=response_obj.read().decode('utf-8')
print(html_code)

三、自定义header

自定义header,就是在构造Request对象时多传入headers参数

header与是get方法还是post方法是没有关联的;也就是说post方法想自定义头部,那么在post的基础方多传入headers参数即可

import urllib.request

url_request="http://10.10.6.92/Pages/login.htm"
header_selfdefine={
     'Host':'10.10.6.92',
     'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:59.0) Gecko/20100101 Firefox/59.0',
     'Accept': '*/*',
     'Accept-Language': 'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2',
     'Accept-Encoding': 'gzip, deflate',
     'Referer': 'http://10.10.6.92/Pages/login.htm'
}

request_obj=urllib.request.Request(url=url_request,headers=header_selfdefine)
response_obj=urllib.request.urlopen(request_obj)
html_code=response_obj.read().decode('utf-8')
print(html_code)

四、使用代理

使用代理的关键是下边中间的四行代码

同样强调使用代理和是get方法,还是post方法,还是使用代理都没有关联

import urllib.request

url_request="http://10.10.6.92/Pages/login.htm"

proxy={'http':'http://127.0.0.1:8080'}
proxy_h=urllib.request.ProxyHandler(proxy)
opener=urllib.request.build_opener(proxy_h)
urllib.request.install_opener(opener)

request_obj=urllib.request.Request(url=url_request)
response_obj=urllib.request.urlopen(request_obj)
html_code=response_obj.read().decode('utf-8')
print(html_code)

猜你喜欢

转载自www.cnblogs.com/lsdb/p/9052257.html