对urllib 的理解

它是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'))

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容