具体步骤:
1.指定url网址
2.发送请求,访问网址
3.获取响应数据
4.持久化存储,保存在数据库或本地
1.下面是访问的bilibili的网址(可以直接复制到python文件)
1.1代码块
#导入requests模块import requestsif __name__=='__main__':#step_1:指定url网址web = '/'#step_2:发送请求,访问网址#使用requests.get方法,用的url参数,把web传入url。get方法会返回一个响应对象,传入responseresponse = requests.get(url=web)#step_3:获取响应数据page_text =response.textprint(page_text)#step_4:持久化存储# 存在本地 编码存入with open('./bilibili.html','w',encoding='utf-8') as fp:fp.write(page_text)print('爬取成功')
1.2操作步骤截图
2.下面是访问的动态的地址(可以直接复制到python文件)
import requestsif __name__ == '__main__':#step_1:指定url,query翻译查询url='/sogou'#把静态的改为动态的,用字典进行封装keyword = input('please input keyworld:')#dict={key1:value1,}用字典封装param = {'query':keyword,}#UA伪装 把user-agent伪装成 浏览器访问的样子header = {'user-agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3884.400 QQBrowser/10.8.4560.400'}#step_2:请求网址,响应response = requests.get(url=url,params=param,headers=header)#step_3:保存响应数据page_text = response.text#step_4:持久化存储filename = keyword+'.html'with open(filename,'w',encoding='utf-8') as fp:fp.write(page_text)print(filename,'网页采集器成功')