模拟人的行为去访问站点,或带回一些与站点相关的信息
1.模拟请求
2.数据解析
3.数据保存
urllib.request.urlopen('http://www.baidu.com')
Python 内置的一个 HTTP 请求库
打开和浏览 URL 中的内容
包含 urllib.request 发生的错误或异常
解析 URL
解析 robots.txt 文件
url = 'https://www.baidu.com/img/test.png'resp = urllib.request.urlopen(url)pic = resp.read()with open('local_test.png', 'wb') as f:f.write(pic)
全局取消证书验证
ssl._create_default_https_context = ssl._create_unverified_context
使用ssl创建未经验证的上下文,在urlopen()中传入上下文参数
context = ssl._create_unverified_context()resp=urllib.request.urlopen(url,context=context)
调用
urllib.request.urlretrieve()函数直接进行下载
urllib.request.urlretrieve(url, 'local_test.png')
urllib.request.Request(get_url)
将字典形式的数据转换为查询字符串
把 GET 请求后跟着的查询字符串反序列化为字典
把 GET 请求后跟着的查询字符串反序列化为列表
urllib.request.Request(post_url,data)
把请求头都塞到字典里,在实例化 Request 对象的时候传入
urllib.request.Request(header_url, headers=headers)
通过 Request 对象的 add_header()方法一个个添加
延迟每次发起请求的时间,用 time 模块的 sleep(秒)函数休眠
轮换代理 IP 去访问目标网站
a)创建代理处理器
proxy_support = urllib.request.ProxyHandler({'http':'21.141.13.43:80'})
b)定制,创建一个opener
opener = urllib.request.build_opener(proxy_support)
c)安装opener
urllib.request.install_opener(opener)
a.实例化CookieJar对象
cookie = cookiejar.CookieJar()
b.创建Cookie处理器
handler = urllib.request.HTTPCookieProcessor(cookie)
c.通过CookieHandler创建opener
opener = urllib.request.build_opener(handler)
d.打开网页
resp = opener.open('http://www.baidu.com')
e.获得Cookie
cookie
a.用于保存Cookie的文件
cookie_file = 'cookie.txt'
b.创建MozillaCookieJar对象保存Cookie
cookie = cookiejar.MozillaCookieJar(cookie_file)
c.创建Cookie处理器
handler = urllib.request.HTTPCookieProcessor(cookie)
d.通过CookieHandler创建opener
opener = urllib.request.build_opener(handler)
e.打开网页
resp = opener.open('http://www.baidu.com')
f.保存Cookie到文件中
cookie.save(ignore_discard=True, ignore_expires=True)
a.创建MozillaCookieJar对象保存Cookie
cookie = cookiejar.MozillaCookieJar(cookie_file)
b.从文件中读取Cookie内容
cookie.load(cookie_file, ignore_expires=True, ignore_discard=True)
c.创建Cookie处理器
handler = urllib.request.HTTPCookieProcessor(cookie)
d.通过CookieHandler创建opener
opener = urllib.request.build_opener(handler)
e.打开网页
resp = opener.open('http://www.baidu.com')
将 URL 拆分成六大组件
和 urlparse 函数类似,只是不会单独拆分 params 部分
接收一个可迭代的对象,长度为 7,以此构造一个 URL
接收一个可迭代的对象,长度为 6,以此构造一个 URL
会分析基础链接的 scheme、netloc 和 path 的内容,并对新链接缺失的部分进行补充
1.urllib.parse 模块的quote 函数
URL 中的中文字符转换为 URL 编码
2.urllib.parse 模块的unquote 函数
对 URL 进行解码
联系客服