requests模块:python中原生的一款基于网络请求的模块,功能非常强大,简单便捷,效率极高
作用:模拟浏览器发请求
如何使用:
指定url,发起请求,获取响应数据,持久化存储
import requests
if __name__ == "__main__":
# 指定url
url = "https://www.sogou.com/"
# 发送请求
response = requests.get(url)
# 获取响应数据
pageText = response.text
print(pageText)
# 持久化存储
with open("./sougou.html", "w", encoding="utf-8") as fp:
fp.write(pageText)
UA:User-Agent(请求载体的身份标识)
UA伪装:门户网站的服务器会检测对应请求的载体身份标识,如果检测到请求的载体身份标识为某一款浏览,说明该请求是个正常的请求,但是如果检测到请求的载体身份标识不是基于某款浏览器的,则表示该请求为不正常的请求(爬虫),服务器端就很有可能拒绝该次请求
# 简易网页采集器
import requests
if __name__ == "__main__":
# UA伪装
headers={"User-Agent": ... (具体查看浏览器)}
# 指定url
url="https://www.sogou.com/web?"
key=input()
param={
'query': key
}
# 发送请求
response=requests.get(url,param,headers=headers)
# 获取响应数据
pageText=response.text
# 持久化存储
with open("./sousuo.html","w",encoding="utf-8") as fp:
fp.write(pageText)
# 百度翻译
import json
import requests
if __name__ == "__main__":
# UA伪装
headers={"User-Agent": ... (具体查看浏览器)}
# 指定url
postUrl="https://fanyi.baidu.com/sug"
# post请求参数处理
data = {
"kw": "dog"
}
# 发送请求
response=requests.post(url=postUrl,data=data,headers=headers)
# 获取响应数据
dicObj=response.json()
# 持久化存储
fp=open("./fanyi.json","w",encoding="utf-8")
json.dump(dicObj,fp=fp,ensure_ascii=False)
# 豆瓣电影
import json
import requests
if __name__ == "__main__":
headers = {
"User-Agent": ... (具体查看浏览器)
}
url="https://movie.douban.com/j/chart/top_list"
param={
"type":"17",
"interval_id":"100:90",
"action":"",
"start":"0", # 从库中的第几部电影去取
"limit":"20"
}
response=requests.get(url=url,params=param,headers=headers)
listData=response.json()
fp=open("./douban.json","w",encoding="utf-8")
json.dump(listData,fp=fp,ensure_ascii=False)
数据解析原理概述:解析的局部的文本内容都会在标签之间或者标签对应的属性中进行存储
编码流程:
指定url,发起请求,获取响应数据,数据解析,持久化存储
单字符:
.:除换行以外所有字符
[]:[aoe] [a-z] 匹配集合中任意一个字符
\d:数字 [0-9]
\D:非数字
\w:数字、字母、下划线、中文
\W:非\w
\s:所有的空白字符包括空格、制表符、换行页等等
\S:非空白数量修饰:
*:任意多次
+:至少1次
?:可有可无,0次或1次
{m}:固定m次
{m,}:至少m次
{m,n}:m-n次边界:
^:以某某开头
$:以某某结尾分组:
(ab)贪婪模式:
.*非贪婪模式:
.*?
re.I:忽略大小写
re.S:单行匹配
re.M:多行匹配
re.sub(正则表达式,替换内容,字符串)
import re
import os
import requests
if __name__ == "__main__":
# 创建文件夹存放图片
if not os.path.exists("./tupian"):
os.mkdir("./tupian")
# UA伪装
headers = {
"User-Agent": ... (具体查看浏览器)
}
# 指定url
url = "https://www.qiushibaike.com/imgrank/"
# 使用通用爬虫对url对应的一整张页面进行爬取
pageText=requests.get(url=url,headers=headers).text
# 使用聚焦爬虫将页面中所有的图片进行解析
ex = '.*?
'
imgSrcList=re.findall(ex,pageText,re.S)
for src in imgSrcList:
# 完善图片url
src="https:"+src
srcContent=requests.get(url=src,headers=headers).content
# 生成图片名称
imgName=src.split("/")[-1]
# 图片存储路径
imgPath="./tupian/"+imgName
# 持久化存储
with open(imgPath,"wb") as fp:
fp.write(srcContent)
print(imgName+"下载成功!")
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
bs4解析
- 实例化一个
BeautifulSoup对象,并且将页面源码数据加载到该对象中 - 通过调用
BeautifulSoup对象中相关的属性或者方法进行标签定位和数据提取
xpath解析
最常用且最便捷高效的一种解析方式。
xpath解析原理:
- 实例化一个
etree的对象,且需要将被解析的页面源码数据加载到该对象中 - 调用
etree对象中的xpath方法结合着xpath表达式实现标签的定位和内容的捕获
xpath表达式:
-
/ :表示的是从根节点开始定位,代表一个层级
-
// :表示多个层级,可以表示从任意位置开始定位
-
属性定位 :eg://div[@class='song']
-
索引定位 :eg://div[@class='song']/p[3] 索引是从1开始的
-
取文本 :
/text():获取的是标签中直系的文本内容
//text():标签中非直系的文本内容(所有的文本内容)
-
取属性 :eg:/@src(属性值)
# 图片下载
from lxml import etree
import requests
import os
if __name__ == "__main__":
if not os.path.exists('./picture'):
os.mkdir('./picture')
# UA伪装
headers = {
"User-Agent": ... (具体查看浏览器)
}
url="https://pic.netbian.com/4kfengjing/"
response=requests.get(url=url,headers=headers)
#response.encoding="utf-8"
pageText=response.text
tree=etree.HTML(pageText)
liList=tree.xpath('//div[@class="slist"]//li')
for li in liList:
imgSrc="https://pic.netbian.com/"+li.xpath('./a/img/@src')[0]
imgName=li.xpath('./a/img/@alt')[0]+".jpg"
imgName=imgName.encode('iso-8859-1').decode('gbk')
imgCon=requests.get(url=imgSrc,headers=headers).content
picPath="./picture/"+imgName
with open(picPath,"wb") as fp:
fp.write(imgCon)
print(imgName+"下载完成!")
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
# 城市获取
from lxml import etree
import requests
if __name__ == "__main__":
# UA伪装
headers = {
"User-Agent": ... (具体查看浏览器)
}
url="https://www.aqistudy.cn/historydata/"
pageText=requests.get(url=url,headers=headers).text
tree=etree.HTML(pageText)
liList=tree.xpath('//div[@class="hot"]//li')
hotCity=[]
for li in liList:
city=li.xpath('./a/text()')[0]
hotCity.append(city)
print(hotCity)
print(len(hotCity))
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
模拟登录
爬取基于某些用户的用户信息。
需求:对人人网进行模拟登录。
- 点击登录按钮之后会发起一个post请求
- post请求中会携带登录之前录入的相关的登录信息(用户名,密码,验证码…)一
- 验证码:每次请求都会变化
需求:爬取当前用户的相关的用户信息(个人主页中显示的用户信息)
http/ https协议特性:无状态。
没有请求到对应页面数据的原因:发起的第二次基于个人主页页面请求的时候,服务器端并不知道该此请求是基于登录状态下的请求。
cookie:用来让服务器端记录客户端的相关状态。
- 手动处理:通过抓包工具获取cookie值,将该值封装到headers中。(不建议)
- 自动处理:
cookie值的来源是哪里?模拟登录post请求后,由服务器端创建。
session会话对象:
作用:
1.可以进行请求的发送。
2.如果请求过程中产生了cookie,则该cookie会被自动存储/携带在该session对象中
使用:
1.创建一个session对象:session = requests.Session()
2.使用session对象进行模拟登录post请求的发送(cookie就会被存储在session中)
3.session对象对个人主页对应的get请求进行发送(携带了cookie)