request的简介
- request模块:python中原生的一款基于昂罗请求的模块,功能强大、操作简单、效率及高。
- 功能:模拟浏览器发出请求。
request的使用(request模块的使用流程)
爬虫案例一——爬取搜狗页面数据
import requests
url = 'https://www.sogou.com/'
response = requests.get(url = url)
page_text = response.text
print(page_text)
with open('./sougou.html', 'w', encoding = 'utf-8') as fp:
fp.write(page_text)
print("爬取结束!")
爬虫案例二——简单网页采集器
import requests
url = 'https://www.sogou.com/web'
headers = {
'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36 SLBrowser/9.0.0.10191 SLBChan/12'
}
kw = input('enter a word:')
param = {
'query': kw
}
response = requests.get(url = url,params=param,headers=headers)
page_text = response.text
fileName = kw+'.html'
with open(fileName, 'w', encoding = 'utf-8') as fp:
fp.write(page_text)
print(fileName, "爬取结束!")
爬虫案例三——百度翻译
import json
import requests
post_url = 'https://fanyi.baidu.com/sug'
headers = {
'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36 SLBrowser/9.0.0.10191 SLBChan/12'
}
word = input('enter a word:')
data = {
'kw': word
}
response = requests.post(url = post_url,data=data,headers=headers)
dic_obj = response.json()
print(dic_obj)
fileName = word+'.html'
fp = open(fileName, 'w', encoding = 'utf-8')
json.dump(dic_obj, fp = fp, ensure_ascii = False)
print(fileName, "爬取结束!")
爬虫案列四——查询肯德基店面信息
import json
import requests
post_url ='http://www.kfc.com.cn/kfccda/ashx/GetStoreList.ashx?op=keyword'
headers = {
'User-Agent': 'Mozilla / 5.0(WindowsNT10.0;Win64;x64) AppleWebKit / 537.36(KHTML, likeGecko) Chrome / 90.0.4430.212Safari / 537.36'
}
keyword = input('enter a address:')
params = {
'cname': '',
'pid': '',
'keyword': keyword,
'pageIndex': '1',
'pageSize': '100',
}
response = requests.post(url = post_url,headers=headers,params=params)
dic_obj = response.json()
print(dic_obj)
fileName = keyword+'.html'
fp = open(fileName, 'w', encoding = 'utf-8')
json.dump(dic_obj, fp = fp, ensure_ascii = False)
print(fileName, "爬取结束!")