爬虫学习-第三篇

首先感谢崔庆才博主的文章,以下信息都是在其文章与《python3网络爬虫开发实战》书中摘抄出的https://cuiqingcai.com

"""
Version: 0.1
Author: freshbin
Date: 2019年8月23日
"""

print("=================================urllib start================================================")

# import socket
# import urllib.request
# import urllib.parse
# import urllib.error

# 爬取网页
# response = urllib.request.urlopen('https://www.python.org')
# print(response.status)
# print(response.getheaders())
# print(response.getheader('Server'))

# 加入参数 data
# data = bytes(urllib.parse.urlencode({'word': 'hello'}), encoding='utf-8')
# response = urllib.request.urlopen('http://httpbin.org/post', data=data)
# print(response.read())

# 超时处理 timeout参数
# try:
#     response = urllib.request.urlopen('http://httpbin.org/get', timeout=0.1)
# except urllib.error.URLError as e:
#     if isinstance(e.reason, socket.timeout):
#         print('TIME OUT')

# 其他参数 cafile(CA证书) capath(CA证书路径)
# 更详细用法见官方文档:https://docs.python.org/3/library/urllib.request.html

print("=================================urllib end================================================")





print("=================================requests start================================================")
# Request
# request = urllib.request.Request('https://python.org')
# response = urllib.request.urlopen(request) # 传入一个Request对象
# print(response.read().decode('utf-8'))

# Request构造方法包含六个参数
'''
第一个参数url用于请求URL,这是必传参数,其他都是可选参数。
第二个参数data如果要穿,必须穿bytes(字节流)类型的。如果它是字段,可以先用urllib.parse模块里的urlencode()编码。
第三个参数headers是一个字典,它就是请求头,我们可以在构造请求时通过headers参数直接构造,也可以通过请求实例的add_header()方法添加
添加请求头最常用的用法就是通过修改User-Agent来伪装浏览器,默认的User-Agent是Python-urllib,我们可以通过修改它来伪装浏览器。
比如要伪装火狐浏览器,你可以把它设为:
Mozilla/5.0 (X11; U; Linux i688) Gecko/20071127 Firefox/2.0.0.11
第四个参数origin_req_host指的是请求方的host名称或者IP地址
第五个参数unverifiable表示这个请求是否是无法验证的,默认是False,意思就是说用户没有足够权限来选择接收这个请求的结果。
例如,我们请求一个HTML文档中的图片,但是我么你没有自动抓取图像的权限,这是unverifiable的值就是True。
第六个参数method是一个字符串,用来指示请求使用的方法,比如GET/POST和PUT等。
'''

# 基本用法
# from urllib import request,parse
#
# url = 'http://httpbin.org/post'
# headers = {
#     'User-Agent': 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)',
#     'Host': 'httpbin.org'
# }
# dict = {
#     'name': 'Germey'
# }
# data = bytes(parse.urlencode(dict), encoding='utf8')
# req = request.Request(url=url, data=data, headers=headers, method='POST')
# response = request.urlopen(req)
# print(response.read().decode('utf-8'))


# 高级用法 Handler
'''
urllib.request模块里的BaseHandler类是所有Handler的父类,见https://docs.python.org/3/library/urllib.request.html#urllib.request.BaseHandler
还有一个比较重要的类是OpenerDirector,urlopen()就是urllib提供的一个Opener,Oener与Handler的关系:利用Handler来构建Opener
'''

# 以下是用一些用法
# 1、验证  场景:有些网站需要登录之后才能查看页面
# from urllib.request import HTTPPasswordMgrWithDefaultRealm, HTTPBasicAuthHandler, build_opener
# from urllib.error import URLError
#
# username = 'username'
# password = 'password'
# url = 'http://localhost:5000/'
#
# p = HTTPPasswordMgrWithDefaultRealm()
# p.add_password(None, url, username, password)
# auth_hanler = HTTPBasicAuthHandler(p)
# opener = build_opener(auth_hanler)
#
# try:
#     result = opener.open(url)
#     html = result.read().decode('utf-8')
#     print(html)
# except URLError as e:
#     print(e.reason)

# 代理
# from urllib.error import URLError
# from urllib.request import ProxyHandler, build_opener
#
# proxy_handler = ProxyHandler({
#     'http': 'http://127.0.0.1:9743',
#     'htpps': 'https://127.0.0.1:9743'
# })
# opener = build_opener(proxy_handler)
#
# try:
#     response = opener.open('https://www.baidu.com')
#     print(response.read().decode('utf-8'))
# except URLError as e:
#     print(e.reason)

# Cookies
import http.cookiejar, urllib.request

# 写cookie
# filename = 'cookies.txt'
# cookie = http.cookiejar.MozillaCookieJar(filename) # MozillaCookieJar格式
# cookie = http.cookiejar.LWPCookieJar(filename) # LWPCookieJar格式的文件
# handler = urllib.request.HTTPCookieProcessor(cookie)
# opener = urllib.request.build_opener(handler)
# response = opener.open('http://www.baidu.com')
# cookie.save(ignore_discard=True, ignore_expires=True)

# 读取cookie
cookie = http.cookiejar.LWPCookieJar()
cookie.load('cookies.txt', ignore_discard=True, ignore_expires=True)
handler = urllib.request.HTTPCookieProcessor(cookie)
opener = urllib.request.build_opener(handler)
response = opener.open('http://www.baidu.com')
print(response.read().decode('utf-8'))

'''
以上便是urllib库中request模块的基本用法
更多说明见官方文档:https://docs.python.org/3/library/urllib.request.html#basehandler-objects
'''
print("=================================requests end================================================")

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值