python网络爬虫应用_Python网络爬虫(requests模块应用1)
一、什么是requests模块?
requests模块是python中原生的基于网络请求的模块,其主要作用是用来模拟浏览器发起请求。功能强大,用法简洁高效。在爬虫领域中占据着半壁江山的地位。
二、为什么要使用requests模块
因为在使用urllib模块的时候,会有诸多不便之处,总结如下:
手动处理url编码
手动处理post请求参数
处理cookie和代理操作繁琐
......
使用requests模块:
自动处理url编码
自动处理post请求参数
简化cookie和代理操作
......
三、如何使用requests模块
安装:
pip install requests
使用流程
指定url
基于requests模块发起请求
获取响应对象中的数据值
持久化存储
四、基于requests模块ajax的get请求实例(豆瓣电影评分)
#爬去电影详细内容
importrequests#设置网页请求头信息
headers ={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3573.0 Safari/537.36"}#请求网址
url = "https://movie.douban.com/j/chart/top_list"
#获取前10页内容
for i in range(10):
params={'type': '5','interval_id': '100:90','action': '','start': '0','limit': str(i*20)
}#返回请求结果
res_json = requests.get(url=url, params=params, headers=headers).json()for res inres_json:print(res["title"], res["rating"][0])
五、基于requests模块ajax的post请求(肯德基餐厅数据)
importrequests#请求头
headers ={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3573.0 Safari/537.36"}
url= "http://www.kfc.com.cn/kfccda/ashx/GetStoreList.ashx?op=keyword"city= input("请输入城市?")for page in range(10):
data={'cname': '','pid': '','keyword': city,'pageIndex': page,'pageSize': '10',
}#获取网页信息
res_json = requests.post(url=url, data=data, headers=headers).json()for res in res_json["Table1"]:
detail_dict={"storeName": res["storeName"],"addrs": res["addressDetail"]
}print(detail_dict)
六、基于requests模块请求(图片存取的两种方式)
需求:图片地址:https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=4123503812,4090072703&fm=26&gp=0.jpg
6.1 通过request获取图片,可以设置UA进行伪装
#方式一:
importrequests#图片url
url = "https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=4123503812,4090072703&fm=26&gp=0.jpg"headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3573.0 Safari/537.36"}
res= requests.get(url, headers=headers).content#print(res)
#保存图片
with open("1.jpg", "wb") as fp:
fp.write(res)
6.2 通过urllib获取图片
#方式二:
from urllib importrequest#图片url
url = "https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=4123503812,4090072703&fm=26&gp=0.jpg"
#保存图片
res = request.urlretrieve(url, filename="./2.jpg")
七、基于requests模块综合练习(国家药监局)
需求:爬取国家药品监督管理总局中基于中华人民共和国化妆品生产许可证相关数据http://125.35.6.84:81/xk/
importrequestsfrom fake_useragent importUserAgent
ua= UserAgent(use_cache_server=False,verify_ssl=False).random
headers={'User-Agent':ua
}
url= 'http://125.35.6.84:81/xk/itownet/portalAction.do?method=getXkzsList'pageNum= 3
for page in range(3,5):
data={'on': 'true','page': str(page),'pageSize': '15','productName':'','conditionType': '1','applyname':'','applysn':''}
json_text= requests.post(url=url,data=data,headers=headers).json()
all_id_list=[]for dict in json_text['list']:
id= dict['ID']#用于二级页面数据获取
#下列详情信息可以在二级页面中获取
#name = dict['EPS_NAME']
#product = dict['PRODUCT_SN']
#man_name = dict['QF_MANAGER_NAME']
#d1 = dict['XC_DATE']
#d2 = dict['XK_DATE']
all_id_list.append(id)#该url是一个ajax的post请求
post_url = 'http://125.35.6.84:81/xk/itownet/portalAction.do?method=getXkzsById'
for id inall_id_list:
post_data={'id':id
}
response= requests.post(url=post_url,data=post_data,headers=headers)#该请求响应回来的数据有两个,一个是基于text,一个是基于json的,所以可以根据content-type,来获取指定的响应数据
if response.headers['Content-Type'] == 'application/json;charset=UTF-8':#print(response.json())
#进行json解析
json_text =response.json()print(json_text['businessPerson'])
方式一
方式二:
importjsonimportrequestsdefget_url_id(url, headers):#网页ID列表
id_list =[]#爬取5页数据
for page in range(5):
data={'on': 'true','page': str(page),'pageSize': '15','productName': '','conditionType': '1','applyname': '','applysn': ''}#获取所有的数据
res_dict = requests.post(url=url, data=data, headers=headers).json()for res in res_dict["list"]:
id_list.append(res["ID"])#返回id列表,里面存放所有详情页id
returnid_list#获取详情页信息
defget_detail(url, headers, id_list):#遍历id列表
for id inid_list:
data= {'id': id}
res_dict= requests.post(url=url, headers=headers, data=data).json()
content={"epsName": res_dict.get("epsName"),"businessPerson": res_dict.get("businessPerson")
}print(content)#保存内容到文件
f = open("detail.txt", encoding="utf-8", mode="a")
json.dump(content, f, ensure_ascii=False)
#with open('detail.json','w',encoding='utf-8') as fp:
# json.dump作用:
# 将字典、列表dump成满足json格式的字符串
#json.dump(data,fp,ensure_ascii=False)
if __name__ == '__main__':#获取网页ID
id_url = "http://125.35.6.84:81/xk/itownet/portalAction.do?method=getXkzsList"
#网页详情
detail_url = "http://125.35.6.84:81/xk/itownet/portalAction.do?method=getXkzsById"
#请求头信息
headers ={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3573.0 Safari/537.36"}#获取id列表
id_list =get_url_id(id_url, headers)#获取详情内容更
get_detail(detail_url, headers, id_list)
python网络爬虫应用_Python网络爬虫(requests模块应用1)相关推荐
- python页面调用接口_python调用接口——requests模块
前提:安装pip install requests 导入import requests 1.get请求 result=requests.get(url,d).json() 或 .text 2. ...
- python sub 不区分大小写_Python网络爬虫入门篇
1. 预备知识 学习者需要预先掌握Python的数字类型.字符串类型.分支.循环.函数.列表类型.字典类型.文件和第三方库使用等概念和编程方法. Python入门篇:https://www.cnblo ...
- python 爬虫框架_Python网络爬虫-scrapy框架的使用
1. Scrapy 1.1 Scrapy框架的安装 Scrapy是一个十分强大的爬虫框架,依赖的库比较多,至少需要依赖的库有Twisted .lxml和pyOpenSSL.在不同的平台环境下,它所依赖 ...
- python网络爬虫系列(四)——requests模块
requests模块 知识点: 掌握 headers参数的使用 掌握 发送带参数的请求 掌握 headers中携带cookie 掌握 cookies参数的使用 掌握 cookieJar的转换方法 掌握 ...
- python 爬虫论_Python网络爬虫(理论篇)
欢迎关注公众号:Python爬虫数据分析挖掘,回复[开源源码]免费获取更多开源项目源码 网络爬虫的组成 网络爬虫由控制节点,爬虫节点,资源库构成. 网络爬虫的控制节点和爬虫节点的结构关系 控制节点(爬 ...
- python网络爬虫学习_python网络爬虫学习笔记
介绍: 网络爬虫的名字非常有意思,英文名称web spider. 真得非常形象.蜘蛛结网为了获取食物,而我们的爬虫程序,也是为了获取网络上的资源. 这篇blog是本人学习过程中的记录.学习过程中,使用 ...
- python网络爬虫应用_python网络爬虫应用实战
原标题:python网络爬虫应用实战 Python这门编程语言包罗万象,可以说掌握了python,除了一些特殊环境和高度的性能要求,你可以用它做任何事. Python作为一门脚本语言,它灵活.易用.易 ...
- 豆瓣python网络数据采集器代理_Python 网络数据采集1
_-coding:utf-8-- ''' Urllib模块:一个基于Http 访问请求的Python模块库,包括以下: 1.urllib.request -- 请求模块 2.urllib.error ...
- python爬虫归纳_Python归纳 | 爬虫基础知识
1. urllib模块库 Urllib是python内置的HTTP请求库,urllib标准库一共包含以下子包: urllib.error 由urllib.request引发的异常类 urllib.pa ...
最新文章
- C#设计模式-1、适配器模式(Adapter Pattern)(转载)
- yolov3模型识别不出训练图片_YOLOv3训练自己的模型
- Django框架视图类
- SQLl中的left join、right join、inner join详解
- CoreJava 笔记总结-第六章 接口、lambda表达式与内部类
- 深入解读RabbitMQ工作原理及简单使用
- linux 下显卡优化,[转载]Linux 下 NVIDIA 显卡闭源驱动的一些优化
- 最初语音识别率只有60%,如今坐拥5亿用户,这款AI产品是怎么做到的?
- Spark SQL运行架构
- 大华监控摄像机接入到小程序、公众号、网站视频直播配置流程
- 湿空气性质计算,随笔与学习记录 (4.空气比容,空气密度)
- 给爱车安装一台GPS,贴身“保镖”保护爱车
- 阳光沙滩博客系统后端api
- 【防火墙_动态路由-OSPF】
- 腾讯云个人账号实名认证图文详情 新手必看教程
- 淘宝直通车什么情况能退款?怎么退?
- c语言改错题字符串a放在b后面,C语言程序改错题汇总.doc
- 复位的recovery time和removal time
- 不懂SpringApplication生命周期事件?那就等于不会Spring Boot嘛
- 宽带自动拨号(无路由器)