02requests
流程
指定url,UA,quary等
发起请求
获取响应
持久化存储
注意
- 百度不进行UA伪装无法获取网页内容,是乱码,bing,sougou可以,既示例1
- 不进行UA伪装无法实现网页搜索,既示例2
- user-agent不要用edge抓包,没有,用搜狗:F12进入开发者,F5刷新界面,点网络,随便点一个包拉到最下面
示例
- 获取某个网页
//抓取一个页面
#coding:utf-8
import requests
if __name__=="__main__":
#指定url
url="https://www.sogou.com/"
#发起请求
response=requests.get(url=url)
#获取字符串形式的响应
page_text=response.text
# print(page_text)
#持久化存储
with open("./index.html",'w',encoding='utf-8') as fp:
fp.write(page_text)
print("爬取结束")
- 简易网页搜索器
# 网页采集器
# coding:utf-8
import requests
if __name__=="__main__":
url="https://www.sogou.com/web"
content=input("请输入要搜索什么")
params={
'query':content
}
headers = {
'User-Agent': "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.87 Safari/537.36 SE 2.X MetaSr 1.0"
}
response=requests.get(url=url,params=params,headers=headers)
page_text=response.text
# print(page_text)
with open("./index.html",'w',encoding='utf-8') as fp:
fp.write(page_text)
print("爬取结束")