想吃各地得美食,你可否了解呢。那么我们今天就来看一下,爬虫怎么让我们见识到各地得美食得。
首先我们先打开美团网,这里我们以爬取长沙的美食数据为例。通过查看源代码,查找目标信息位置。
具体代码如下:
import csv
import requests
import json
import re
def one_level(url,headers):
meishi_dict={}
response=requests.get(url,headers=headers)
avgScore=re.findall(r'"avgScore".*?),',response.text)
shopname=re.findall(r'"frontImg".*?title".*?),',response.text)
allCommentNum=re.findall(r'"allCommentNum"\d+),',response.text)
address=re.findall(r'"address".*?),',response.text)
avgPrice=re.findall(r'"avgPrice"\d+),',response.text)
urlid=re.findall(r'"poiId"\d+),',response.text)
two_url=[]
for k in urlid:
a='https://www.meituan.com/meishi/'+str(k)+'/'
two_url.append(a)
meishi_all_list=[]
for i in range(len(shopname)):
meishi_list=[]
meishi_list.append(shopname[i])
meishi_list.append(avgScore[i])
meishi_list.append(allCommentNum[i])
meishi_list.append(address[i])
meishi_list.append(avgPrice[i])
meishi_list.append(two_url[i])
meishi_all_list.append(meishi_list)
return meishi_all_list,two_url
def two_level(meishi_all_list,two_url,headers):
for i in meishi_all_list:
new_url=i[5]
response=requests.get(new_url,headers=headers)
phone=re.findall(r'"phone".*?),',str(response.text))
openTime=re.findall(r'"openTime".*?),',str(response.text))
i.append(phone)
i.append(openTime)
writer_to_file(meishi_all_list)
return meishi_all_list
def writer_to_file(meishi_all_list):
with open('food.csv','a',newline='',encoding='utf-8')as f:
write=csv.writer(f)
write.writerows(meishi_all_list)
def main():
for i in range(1,5):
url='https://chs.meituan.com/meishi/pn' + str(i) + '/'
headers={'User-Agent':'headers里面添加自已的cookie'}
a,b=one_level(url,headers)
two_level(a,b,headers)
if __name__=='__main__':
main()
通过上述代码,我们就可以获取到美团长沙美食信息数据了。
爬虫爬取过程中,为了防止反爬虫得干扰,一般会使用代理IP。需要联系扣扣:33------72-----------92----------404 |