[TOC]
1.爬取网页
response属性
读取数据
1.读取文件的全部内容,会把读取到的数据赋值给一个列表
data = response.readlines()
2.读取文件的全部内容,会把读取到的数据赋值给一个字符串
data = response.read()
- 读取文件的一行
data = response.readline()
4.encode
将我们看得懂得东西变为看不懂得东西
_decode
将我们看不懂得东西变为看得懂得东西返回当前环境的有关信息
data = response.info()
返回状态码
data = response.getcode()
if response.getcode() ==200 or response.getcode() ==304
返回正在爬取的URL地址
data = response.geturl()
编码(解码),将url中的汉字编码转化为汉字
url="http://***"
newurl = urllib.request.(un)quote(url)
有时候内容编码是Unicode的格式,则需要对其进行编码再解码
content.encode('latin-1').decode('unicode_escape')
改进
decode(“utf-8”,”ignore”)
2.将网页存取到指定文件中
import urllib.request
urllib.request.urlretrieve("url",filename=r"存取的文件地址")
注意:urlretrieve在执行的过程中会产生一些缓存,清除缓存如下操作urllib.request.urlcleanup()
3.模拟浏览器
利用User-Agent,添加headers,使得模拟更加真实1
2
3
4
5
6
7
8
9
10
11import urllib.request
url = " "
headers = {
"User-Agent":" "
}
#设置一个请求体,构建请求对象
req = urllib.request.Request(url,headers=headers)
#发起请求
response = urllib.request.urlopen(req)
data = response.read().decode("utf-8")
print (data)
1 | #保持模拟浏览器登陆状态--cookies |
1 | # 为防止被封IP可以将多个Agent做成列表,多次变换 |
- 请求url的错误处理,防止无法请求url而影响程序
1 | import requests.exceptions import RequestException |
4.设置超时&间隙时间
1 | #在使用urllib或者urllib2时,有可能会等半天资源都下载不下来, |
1 | import urllib.request |
5.HTTP请求
1 | ''' |
Https请求
1 | #抓取HTTPS协议 |
6.抓取网页动态Ajax请求的数据
1 | import ssl |
1 | # 动态数据,在 js文件中有真正的请求url |
- 1.建立需求
- 源代码中没有我们需要的数据
原因:- 1.
Ajax异步加载
:通过多个请求获取数据
(通过XHR筛选出Ajax加载的数据)- 2.数据加密
- 1.
- 源代码中没有我们需要的数据
7.保存文件,数据持久化
1 | import requests |
1 | import os |