python爬虫--requests模块
requests模块
- 安装 :
pip install requests
- 作用:就是用来模拟浏览器上网的。
- 特点:简单,高效
- 其他的爬虫模块(old): urllib模块
一. 使用
- requests模块的使用流程:
- 指定url
- 发起请求
- 获取响应数据
- 持久化存储
#爬取搜狗首页的页面数据
import requests
#1指定url
url = 'https://www.sogou.com/'
#2.发起请求
response = requests.get(url=url)
#3获取响应数据
page_text = response.text #text返回的是字符串类型的数据
#持久化存储
with open('./sogou.html','w',encoding='utf-8') as fp:
fp.write(page_text)
print('over!')
1.get请求使用
- 处理get请求的参数
- 需求:网页采集器
- 反爬机制:UA检测
- 反反爬策略:UA伪装
示例:1
import requests
wd = input('enter a word:')
url = 'https://www.sogou.com/web'
#参数的封装
param = {
'query':wd
}
#UA伪装
headers = {
'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36'
}
response = requests.get(url=url,params=param,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)
print(fileName,'爬取成功!!!')
2.post请求使用
示例2:
#破解百度翻译
url = 'https://fanyi.baidu.com/sug'
word = input('enter a English word:')
#请求参数的封装
data = {
'kw':word
}
#UA伪装
headers = {
'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36'
}
response = requests.post(url=url,data=data,headers=headers)
#text:字符串 json():对象
obj_json = response.json()
print(obj_json)
示例3:
#爬取任意城市对应的肯德基餐厅的位置信息
#动态加载的数据
city = input('enter a cityName:')
url = 'http://www.kfc.com.cn/kfccda/ashx/GetStoreList.ashx?op=keyword'
data = {
"cname": "",
"pid": "",
"keyword": city,
"pageIndex": "2",
"pageSize": "10",
}
#UA伪装
headers = {
'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36'
}
response = requests.post(url=url,headers=headers,data=data)
json_text = response.text
print(json_text)