requests模块
1.网络请求模块
1.urllib模块(古老比较麻烦) 2…requests模块(简单主要)
2.什么是requests模块
requests模块:Python中原生的一款基于网络请求的模块,功能非常强大,简单便捷,效率极高。 requests作用:模拟浏览器发请求
3.requests 如何使用(requests模块的编码流程)
1.指定url 2.发起请求 3.获取响应数据 4.持久化存储
4.环境安装
pip install requests
5.实战编码
1.需求:爬取搜狗首页的页面数据
import requests
if __name__ == "__main__":
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('爬取数据结束!!!')
2.# 需求:爬取搜狗指定词条对应的搜索结果页面(简易网页采集器)
import requests
if __name__=="__main__":
headers={
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.71 Safari/537.36"
}
url="https://www.sogou.com/web"
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,'保存成功!!!')
3#破解百度翻译
import json
import requests
if __name__=="__main__":
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/94.0.4606.71 Safari/537.36"
}
word=input('enter a word:')
data={
"kw":word
}
reapinse=requests.post(url=post_url,data=data,headers=headers)
dic_obj=reapinse.json()
fileName=word+'.json'
fp=open(fileName,'w',encoding='utf-8')
json.dump(dic_obj,fp=fp,ensure_ascii=False)
print("over!!!")
4#爬去豆瓣电影分类排行榜
import requests
import json
if __name__=="__main__":
url='https://movie.douban.com/j/chart/top_list'
param={
"type": "24",
"interval_id": "100:90",
"action":"",
"start": "1",
"limit": "20"
}
headers={
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.71 Safari/537.36"
}
resonse=requests.get(url=url,params=param,headers=headers)
list_data=resonse.json()
fp=open('./d.json','w',encoding='utf-8')
json.dump(list_data,fp=fp,ensure_ascii=False)
print("over!!!")
|