它是python内置的http的请求库,
urrlib.request 请求模块
urllib.error 异常处理模块
urllib.parse url解析模块
urllib.robotparser robots.txt 解析模块协议
python2 和python3 的变化
import urllib2
response = urllib2.open("")
import urllib.request
response = urllib.request.urlopen("")
代码实例:get 请求
import urllib.request
response =urllib.request.urlopen("")
print(response.read().decode('utf-8'))
代码实例: post 请求
import urllib.request
import urllib.parse
data =bytes(urllib.parse.urlencode({'world':'hello'}).encoding ='utf-8')
response = urllib.request.urlopen("网址",data =data)
print(response.read())
超时设置:
import socket
import urllib.request
import urllib.error
try:
response =urllib.request.urlopen("网址",timeout =1)
except urllib.error.URLError as e:
if isinstance(e.eason,socket.timeout):
print(time out")
请求头:
from urllib.parse,request
url = "网址"
headers ={
'User_Agent':' ',
'Host':' '
}
dict = { "name":"xnsui"}
data =bytes(parse.urlencode(dict),encoding="utf-8")
req = request.Request(url=url,data=data,headers=headers,method="POST")
response = request.urlopen(req)
print((response.read().decode('utf-8'))