第二章 requests模块基础
example6: 爬取国家药品监督管理总局中基于中华人民共和国化妆品生产许可证相关数据
#----- 实战代码6:-----
# 综合练习
# 需求:爬取国家药品监督管理总局中基于中华人民共和国化妆品生产许可证相关数据http://125.35.6.84:81/xk/
import requests
import json
from fake_useragent import UserAgent
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 in all_id_list:
post_data = {
'id':id
}
response = requests.post(url=post_url,data=post_data,headers=headers)
if response.headers['Content-Type'] == 'application/json;charset=UTF-8':
#print(response.json())
#进行json解析
json_text = response.json()
print(json_text['businessPerson'])
简化
# 简化
import requests
import json
headers = {
'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36',
}
url = 'http://125.35.6.84:81/xk/itownet/portalAction.do?method=getXkzsList'
id_list = [] # 存储企业的ID
all_data_list = [] # 存储所有的企业的详细数据
for page in range(3,5):
data = {
'on': 'true',
'page': str(page),
'pageSize': '15',
'productName':'',
'conditionType': '1',
'applyname':'',
'applysn':''
}
json_ids = requests.post(url = url, headers = headers, data = data).json()
for dic in json_ids['list']:
id_list.append(dic['ID'])
post_url = 'http://125.35.6.84:81/xk/itownet/portalAction.do?method=getXkzsById'
for id in all_id_list:
post_data = {
'id':id
}
detail_json = requests.post(url=post_url,data=post_data,headers=headers)
all_data_list.append(detail_json)
fp = open('./allData.json','w',encoding='utf-8')
json.dump(all_data_list,fp=fp,ensure_ascii=False)