urllib基本使用 urlopen(),Request

urllib包含的常用模块:
import urllib.request # 打开和读取url请求
import urllib.error # 异常处理模块
import urllib.parse # url解析模块
import urllib.robotparser # robots.txt解析模块

"""
urllib.request.urlopen(url, data=None, [timeout, ]*, cafile=None, capath=None,
cadefault=False, context=None)
url:  需要打开的网址
data:默认为None,当data参数不为空的时候,提交方式为Post。
timeout:设置网站的访问超时时间
直接用urllib.request模块的urlopen()获取页面内容,返回的数据格式为bytes类型,需要decode()解码,转换成str类型

# 1、 get请求
import urllib.request

response = urllib.request.urlopen('http://www.baidu.com/')
print(response.read().decode('utf-8'))

# 2、 post请求
import urllib.request
import urllib.parse

data = bytes(urllib.parse.urlencode({'world':'hello'}),encoding='utf8')
response = urllib.request.urlopen('http://httpbin.org/post',data= data)
print(response.read().decode('utf-8'))

# 3、超时时间
import socket
import urllib.request
import urllib.error

try:
response = urllib.request.urlopen('http://httpbin.org/get',timeout= 1)
except urllib.error.URLError as e:
if isinstance(e.reason,socket.timeout):
print('time out')

urlopen返回对象提供方法:

- read() , readline() ,readlines() , fileno() , close() :对HTTPResponse类型数据进行操作
- info():返回HTTPMessage对象,表示远程服务器返回的头信息
- getcode():返回Http状态码。如果是http请求,200请求成功完成;404网址未找到
- geturl():返回请求的url
- response.status :请求状态码
- response.getheader(): 响应头信息,也可以传参数,获取特定的信息
"""

"""
使用Request
urllib.request.Request(url, data=None, headers={}, method=None)
使用request()来包装请求,再通过urlopen()获取页面。
1、data(默认空):是伴随 url 提交的数据(比如要post的数据),同时 HTTP 请求将从 "GET"方式 改为 "POST"方式。
2、headers(默认空):是一个字典,包含了需要发送的HTTP报头的键值对。
在 HTTP Request 中加入特定的 Header,来构造一个完整的HTTP请求消息。
可以通过调用Request.add_header() 添加/修改一个特定的header 也可以通过调用Request.get_header()来查看已有的header。
"""
url = 'http://httpbin.rog/post'
# 通过 User-Agent 伪装成浏览器
headers = {
'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36',
'Connection': 'keep-alive'
}

dict = {
'name':'Andy'
}

data = bytes(urllib.parse.urlencode(dict),encoding='utf8')

# url 连同data, headers,一起构造Request请求,构造并返回一个Request对象
request = urllib.request.Request(url=url,data=data,headers=headers)

#可以通过调用Request.add_header() 添加/修改一个特定的header
#request.add_header("Connection", "keep-alive")
#可以通过调用Request.get_header()来查看header信息
#print(request.get_header(header_name='Connection'))

# 第一个字母大写,后面的全部小写
#print(request.get_header("User-agent"))

# Request对象作为urlopen()方法的参数,发送给服务器并接收响应
response = urllib.request.urlopen(request)
html = response.read().decode('utf-8')
print(html)


原文地址:https://www.cnblogs.com/AndyChen2015/p/7418053.html