requests
什么是requests模块
python中封装好的一个基于网络请求的模块
作用
用来模拟浏览器发送请求
环境安装
pip install requests
编码流程
- 指定 url
- 发起请求
- 获取响应数据
- 持久化存储
爬取搜狗首页的页面源码数据
#爬取搜狗首页的页面源码数据
import requests
#1.指定url
url = 'https://www.sogou.com/'
#2.请求发送get:get返回值是一个响应对象
response = requests.get(url=url)
#3.获取响应数据
page_text = response.text #返回的是字符串形式的响应数据
#4.持久化存储
with open('sogou.html','w',encoding='utf-8') as fp:
fp.write(page_text)
#实现一个简易的网页采集器
#需要让url携带的参数动态化
url = 'https://www.sogou.com/web'
#实现参数动态化
wd = input('enter a key:')
params = {
'query':wd
}
#在请求中需要将请求参数对应的字典作用到params这个get方法的参数中
response = requests.get(url=url,params=params)
page_text = response.text
fileName = wd+'.html'
with open(fileName,'w',encoding='utf-8') as fp:
fp.write(page_text)
- 上述代码执行后发现:
- 1.出现了乱码
- 2.数据量级不对
#解决乱码
url = 'https://www.sogou.com/web'
#实现参数动态化
wd = input('enter a key:')
params = {
'query':wd
}
#在请求中需要将请求参数对应的字典作用到params这个get方法的参数中
response = requests.get(url=url,params=params)
response.encoding = 'utf-8' #修改响应数据的编码格式
page_text = response.text
fileName = wd+'.html'
with open(fileName,'w',encoding='utf-8') as fp:
fp.write(page_text)
- UA检测:门户网站通过检测请求载体的身份标识判定改请求是否为爬虫发起的请求
- UA伪装:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36
#解决UA检测
url = 'https://www.sogou.com/web'
#实现参数动态化
wd = input('enter a key:')
params = {
'query':wd
}
headers = {
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36'
}
#在请求中需要将请求参数对应的字典作用到params这个get方法的参数中
response = requests.get(url=url,params=params,headers=headers)
response.encoding = 'utf-8' #修改响应数据的编码格式
page_text = response.text
fileName = wd+'.html'
with open(fileName,'w',encoding='utf-8') as fp:
fp.write(page_text)
爬取豆瓣电影中电影的详情数据
- https://movie.douban.com/typerank?type_name=%E7%88%B1%E6%83%85&type=13&interval_id=100:90&action=
- 分析: 当滚动条被滑动到页面底部的时候,当前页面发生了局部刷新(ajax的请求)
url = 'https://movie.douban.com/j/chart/top_list'
start = input('您想从第几部电影开始获取:')
limit = input('您想获取多少电影数据:')
dic = {
'type': '13',
'interval_id': '100:90',
'action': '',
'start': start,
'limit': limit,
}
response = requests.get(url=url,params=dic,headers=headers)
page_text = response.json() #json()返回的是序列化好的实例对象
for dic in page_text:
print(dic['title']+':'+dic['score'])
肯德基餐厅查询
#肯德基餐厅查询http://www.kfc.com.cn/kfccda/storelist/index.aspx
url = 'http://www.kfc.com.cn/kfccda/ashx/GetStoreList.ashx?op=keyword'
for page in range(1,5):
data = {
'cname': '',
'pid': '',
'keyword': '西安',
'pageIndex': str(page),
'pageSize': '10',
}
response = requests.post(url=url,headers=headers,data=data)
print(response.json())
原文地址:https://www.cnblogs.com/5kuishoua666/p/12021656.html
时间: 2024-10-11 21:12:19