Urllib库
2017-12-14 本文已影响0人
原来不语
基本的请求库:

urllib库的一些使用方法
urlopen()方法
urllib.request.urlopen(url, data=None, [timeout, ]*, cafile=None, capath=None, cadefault=False, context=None)
url: 需要打开的网址
data:Post提交的数据
timeout:设置网站的访问超时时间
urlopen返回对象提供方法:
read() , readline() ,readlines() , fileno() , close() :对HTTPResponse类型数据进行操作
info():返回HTTPMessage对象,表示远程服务器返回的头信息
getcode():返回Http状态码。如果是http请求,200请求成功完成;404网址未找到
geturl():返回请求的url
import urllib request
response = urllib.request.urlopen("http://www.baidu.com")
print(response.read().decode('utf-8'))
urllib.parse
以post方式发送
import urllib request
import urllib parse
data = bytes(urllib.parse.urlencode({'word':'hello'}),encoding = 'utf-8')
response = urllib.request.urlopen("http://httpbin.org/post",data = data)
print(response.read[])
response = urllib.request.urlopen("http://httpbin.org/post",timeout = 1)





