爬取肯德基官网的各地区店名及地址 的页码问题
首先代码如下:import requests
import json
import openpyxl
def open_url(url):
headers={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36'}
# kw=input('输入查询地区:')
list1=[]
list2=[]
list3=[]
for i in range(1,5):
data={"cname":"",
"pid":"",
"keyword": "上海",
"pageIndex": i,
"pageSize": "10",
}
response=requests.post(url,data=data,headers=headers)
req=json.loads(response.text)['Table1']
for each in req:
list1.append(each['storeName'])
list2.append(each['addressDetail'])
list3.append(each["provinceName"]+each['cityName'])
result=[]
for i in range(len(list1)):
result.append(,list2,list3])
wb=openpyxl.Workbook()
wa=wb.active
wa['A1']='店名'
wa['B1']='地址'
wa['C1']='位置'
wa.column_dimensions['A'].width = 30
wa.column_dimensions['B'].width = 45
wa.column_dimensions['C'].width = 30
for each in result:
wa.append(each)
wb.save('上海.xlsx')
if __name__=='__main__':
url='http://www.kfc.com.cn/kfccda/ashx/GetStoreList.ashx?op=keyword'
open_url(url)
有一个问题就是在爬取各个地区的时候,想把地区设置成动态的,由于各地区店的数量不同,一页展示十个,所以页数也会不同,应该如何爬取页码数?卡在这个地方不会了,有没有大佬指点一下 本帖最后由 suchocolate 于 2020-7-18 23:29 编辑
get拿到的是json数据(非html),没有办法通过html解析,不过json写了总数目:
num = response.json()['Table']['rowcount']
max = (int(num) // 10) + 2
for i in range(1, max):
xxx
上面是34,除以10取整就是3,加1就是4页能容下,放range里再加1。 import requests
import json
import openpyxl
def open_url(url):
headers={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36'}
global kw
kw=input('输入查询地区:')
list1=[]
list2=[]
list3=[]
for i in range(1,5):
data={"cname":"",
"pid":"",
"keyword": "%s"%(kw),
"pageIndex": i,
"pageSize": "10",
}
response=requests.post(url,data=data,headers=headers)
req=json.loads(response.text)['Table1']
for each in req:
list1.append(each['storeName'])
list2.append(each['addressDetail'])
list3.append(each["provinceName"]+each['cityName'])
result=[]
for i in range(len(list1)):
result.append(,list2,list3])
wb=openpyxl.Workbook()
wa=wb.active
wa['A1']='店名'
wa['B1']='地址'
wa['C1']='位置'
wa.column_dimensions['A'].width = 30
wa.column_dimensions['B'].width = 45
wa.column_dimensions['C'].width = 30
for each in result:
wa.append(each)
wb.save('%s.xlsx'%(kw))
if __name__=='__main__':
url='http://www.kfc.com.cn/kfccda/ashx/GetStoreList.ashx?op=keyword'
open_url(url)
页:
[1]