Python爬虫urllib库(三)
阿里云国内75折 回扣 微信号:monov8 |
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6 |
简介
python自带http请求工具,无需下载
url
组成
- http/https协议
- 主机地址
- 端口
- 路径
- 参数
User Agent
UA介绍:
User Agent中文名为用户代理简称UA它是一个特殊字符串头使得服务器能够识别客户使用的操作系统及版本、CPU类型、浏览器及版本。浏览器内核、浏览器渲染引擎、浏览器语言、浏览器插件等
案例
import urllib.request
# 爬取网站地址
url = 'http://www.baidu.com'
# 模拟浏览器访问
response = urllib.request.urlopen(url)
# 获取相应源码,获取的二进制数据,设置文件编码
content = response.read().decode('UTF-8')
print(content)
# 实现下载,目录为当前目录
urllib.request.urlretrieve(url,'下载文件名称')
# 设置header
hearders = {
'User‐Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, likeGecko) Chrome/74.0.3729.169 Safari/537.36'
}
request = urllib.request.Request(url, headers=hearders)
请求get参数带中文字符转码
# 请求地址
url = 'https://cn.bing.com/search?PC=U316&FORM=CHROMN&q='
# 中文转码unicode
url = url + urllib.parse.quote('周杰伦')
# 处理header编码问题
headers = {
urllib.parse.quote('User‐Agent'): urllib.parse.quote(
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) '
'Chrome/73.0.3683.75 Safari/537.36 ')
}
在请求头中一样存在编码问题所以可以使用
urllib.parse.quote
一样进行编码处理
Get多参数情况
params = {
'name':'周杰伦',
'sex' : '男'
}
paramsStr = urllib.parse.urlencode(params)
POST请求示例
# 百度翻译实例
import json
import urllib.request
url = 'https://fanyi.baidu.com/sug'
# post请求参数必须编码
data = {
'kw': '翻译'
}
data = urllib.parse.urlencode(data).encode('utf‐8')
headers = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36'
}
request = urllib.request.Request(url=url, data=data, headers=headers)
response = urllib.request.urlopen(request)
content = response.read().decode('utf-8')
# 转换成json对象
json.loads(content)
print(content)
# 写入文件中
with open('name'.json','w',encoding='utf‐8')as fp:
fp.write(content)
注意问题,请求参数需要通过
urllib.parse.urlencode(data).encode('utf‐8')
进行编码
with是try catch简写方案会自动调用
fp.close
方法关闭流
异常处理
URLError\HTTPError异常
简介:
- HTTPError类是URLError类的子类
- 导入的包urllib.error.HTTPError
urllib.error.URLError 3. http错误:http错误是针对浏览器无法连接到服务器而增加出来的错误提示。引导并告诉浏览者该页是哪里出
了问题。 - 通过urllib发送请求的时候有可能会发送失败这个时候如果想让你的代码更加的健壮可以通过try‐except进行捕获异常异常有两类URLError\HTTPError
URLError
URLError产生的原因主要有
- 没有网络连接
- 服务器链接失败
- 找不到指定的服务器
请求本身问题
HTTPError
HTTPError是URLError的子类我们发出一个请求时服务器都会对应一个response应答对象其中它包含一个数字"响应状态码"
http服务问题
抛出异常
try:
request = urllib.request.Request(url=url, data=data, headers=headers)
response = urllib.request.urlopen(request)
content = response.read().decode('utf-8')
except urllib.HTTPError as err:
print(err.code)
except urllib.URLError:
print('请求异常')
else:
# 转换成json对象
json.loads(content)
print(content)
动态请求头
动态请求头处理动态代理、动态cookies反爬虫问题
示例代码
eg:
import urllib.request
url = 'http://www.baidu.com'
headers = {
'User ‐ Agent': 'Mozilla / 5.0(Windows NT 10.0;Win64;x64) AppleWebKit / 537.36(KHTML,
likeGecko) Chrome / 74.0.3729.169Safari / 537.36'
}
request = urllib.request.Request(url=url,headers=headers)
#获取handler对象
handler = urllib.request.HTTPHandler()
#构建hander
opener = urllib.request.build_opener(handler)
response = opener.open(request)
print(response.read().decode('utf‐8'))
主要代码
handler = urllib.request.HTTPHandler() opener = urllib.request.build_opener(handler)
模拟构建header请求头
模拟代理
- 代理的常用功能?
- 突破自身IP访问限制访问国外站点。
- 访问一些单位或团体内部资源
扩展:某大学FTP(前提是该代理地址在该资源的允许访问范围之内)使用教育网内地址段免费代理服务 器就可以用于对教育网开放的各类FTP下载上传以及各类资料查询共享等服务。
-
提高访问速度
-
扩展:通常代理服务器都设置一个较大的硬盘缓冲区当有外界的信息通过时同时也将其保存到缓冲区中当其他用户再访问相同的信息时则直接由缓冲区中取出信息传给用户以提高访问速度。
-
隐藏真实IP
扩展:上网者也可以通过这种方法隐藏自己的IP免受攻击。 2.代码配置代理
创建Reuqest对象 创建ProxyHandler对象 用handler对象创建opener对象 使用opener.open函数发送请求
示例代码
import urllib.request
url = 'http://www.baidu.com/s?wd=ip'
headers = {
'User ‐ Agent': 'Mozilla / 5.0(Windows NT 10.0;Win64;x64) AppleWebKit / 537.36(KHTML,
likeGecko) Chrome / 74.0.3729.169Safari / 537.36'
}
request = urllib.request.Request(url=url,headers=headers)
#主要代码模拟ip
proxies = {'http':'117.141.155.244:53281'}
handler = urllib.request.ProxyHandler(proxies=proxies)
opener = urllib.request.build_opener(handler)
response = opener.open(request)
content = response.read().decode('utf‐8')
with open('daili.html','w',encoding='utf‐8')as fp:
fp.write(content)
主要代码
proxies = {'http':'117.141.155.244:53281'} handler = urllib.request.ProxyHandler(proxies=proxies)
设置代理地址
可以使用快代理使用免费ip
代理池
使用ip容器随机取ip进行header代理使用