1. 程式人生 > >Python爬蟲 - 獲取美團美食資料

Python爬蟲 - 獲取美團美食資料

這兩天接觸了一下python爬蟲,根據網上的一些部落格寫了下面的程式碼來抓取美團網上的美食資料,記錄一下。


#from bs4 import BeautifulSoup #解析html或xml檔案的庫
import urllib.request
import csv
import re
import json


csv_file = open("rent.csv","w",encoding='utf-8') 
csv_writer = csv.writer(csv_file, delimiter=',')

class Spider:
	def loadPage(self,page):
		url = "http://gz.meituan.com/meishi/pn"+str(page)+"/"

		#user-Agent頭
		user_agent="Mozilla/5.0 (compatible; MSIE 9.0; Windows NT6.1; Trident/5.0"
		headers = {"User-Agent":user_agent}
		req = urllib.request.Request(url,headers = headers)
		response = urllib.request.urlopen(req)
		html =str(response.read(),'utf-8')

		
		#找到商家資訊的內容為:{"poiId":xxx}
		#re.S 如果沒有re.S,則是隻匹配一行有沒有符合規則的字串,如果沒有則匹配下一行重新匹配
		#如果加上re.S,則是將所有的字串按一個整體進行匹配
		
		pattern = re.compile(r'{"poiId":.*?}',re.S)
		item_list = pattern.findall(html)#獲取資料
			
		#dictinfo = json.loads(item_list[0])#把字串轉化為字典
		
		list = []#存放資料的陣列
		
		for data in item_list:
				dictinfo = json.loads(data)
				csv_writer.writerow([dictinfo["title"],dictinfo["address"],dictinfo["avgScore"],dictinfo["avgPrice"]])
		
		

if __name__ == "__main__":
	mySpider = Spider()
	
	for i in range(1,33):
		print("fecth:Page"+str(i))
		mySpider.loadPage(i)
		
	csv_file.close()