urllib库的使用(一)

#urllib.request是最基本的HTTP请求的方法,它可以模拟浏览器的请求发起过程,它处理授权验证,重定向,浏览器Cookies
#简单示例
import urllib.request
response = urllib.request.urlopen(‘https://www.python.org’)
print(response.read().decode(‘utf-8’))
print(response.status)
#调用read()方法可以得到返回的网页内容,status属性可以得到返回结果的状态码
#最基本的urlopen()方法,可以完成最基本的简单网页的GET请求抓取
#urllib可传递的参数如下
#urllib.request.urlopen(url,data=None,[timeout,]*,cafile=None,capath=None, cadefault=False,context=None)
#1.data参数 是可选参数,如它不是字节流编码格式内容需用bytes()方法转化。
用此参数请求方式是POST方式
import urllib.parse
import urllib.requestdata = bytes(urllib.parse.urlencode({‘word’:‘hello’}),encoding=‘utf-8’)response = urllib.request.urlopen(‘http://httpbin.org/post’,data = data)
print(response.read())
#urllib.parse模块里的urlencode()方法将参数字典转化为字符串,指定编码格式是’utf-8’
#2. timeout参数,(s)它用于设置超时时间,如请求超出设置的这个时间,还没有得到响应,就会抛出异常。不指定就是使用全局默认时间
#出现异常错误用try except语句
import urllib.request
import urllib.errorimport socket
try:
response = urllib.request.urlopen(‘http://httpbin.org/get’,timeout=0.2)
except urllib.error.URLError as e:
if isinstance(e.reason,socket.timeout):
print(‘Time out’)
#cafile 和 capath 这两个参数分别指定CA证书和它的路径,他们在请求HTTPS链接时有用#cadefault参数默认值为False#context参数,ssl.SSLContext类型,用来指定SSL设置

#Request 的用法
import urllib.requestrequest = urllib.request.Request(‘https://python.org’)
response = urllib.request.urlopen(request)
print(response.read().decode(‘utf-8’))
#class urllib.request.Request(url,data=None,headers={},origin_req_host=None,unverifiable=False,method=None)
#第一个参数url是必传参数
#第二个参数data如果要传,必须是bytes(字节流)类型,如是字典,可以先用urllib.parse模块里的urlencode()编码
#第三个参数headers是字典,它是请求头,在构造请求时通过headers参数直接构造,也可通过调用请求实例的add_header()方法添加#添加请求头通常是通过修改User-Agent来伪装浏览器,默认是Python-urllib,通过修改他来伪装浏览器,
#第四个参数指的是请求对方的host名称或者IP地址
#第五个参数默认是False,用户没有足够的权限来选择接受这个请求的结果,
#第六个参数method是一个字符串,用来指示请求使用的方法,例如GET,POST,PUT等
from urllib import request
parseurl = 'http://httpbin.org/post’h
eaders = { ‘User-Agent’:‘Mozilla/4.0 (compatible; MSIE S. S; Windows NT)’, ‘Host’:‘httpbin.org’}
dict = { ‘name’:‘Germey’ }
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’))

猜你喜欢

转载自blog.csdn.net/wg5foc08/article/details/88762753