scrapy爬蟲框架調用百度地圖api數據存入資料庫

scrapy安裝配置不在本文 提及,

1.在開始爬取之前,必須創建一個新的Scrapy項目。進入自定義的項目目錄中,運行下列命令

scrapy startproject mySpider
  • 其中, mySpider 為項目名稱,可以看到將會創建一個 mySpider 文件夾,目錄結構大致如下:
  • 下面來簡單介紹一下各個主要文件的作用:

    scrapy.cfg :項目的配置文件

    mySpider/ :項目的Python模組,將會從這裡引用程式碼

    mySpider/items.py :項目的目標文件

    mySpider/pipelines.py :項目的管道文件

    mySpider/settings.py :項目的設置文件

    mySpider/spiders/ :存儲爬蟲程式碼目錄

     mySpider/spiders/__init__.py :爬蟲主要處理邏輯

2.  今天通過爬蟲調用 百度地圖api來獲取 全國學校的經緯度資訊 併入庫。

     百度地圖介面api ://api.map.baidu.com/place/v2/search?query=小學、中學或者大學&region=地市名字&output=json&ak=你的開發者ak&page_num=頁碼

  1)打開mySpider目錄下的items.py

              Item 定義結構化數據欄位,用來保存爬取到的數據,也是爬取數據後導出的欄位,有點像Python中的dict字典,但是提供了一些額外的保護減少錯誤。

    可以通過創建一個 scrapy.Item 類, 並且定義類型為 scrapy.Field的類屬性來定義一個Item。

    items.py

 1 import scrapy
 2 
 3 
 4 class GetpointItem(scrapy.Item):
 5     # define the fields for your item here like:
 6     # name = scrapy.Field()
 7     name = scrapy.Field()  #學校名稱
 8     lat = scrapy.Field()   #緯度
 9     lng = scrapy.Field()   #經度11     city = scrapy.Field()  #地市
12     area = scrapy.Field()  #區縣
13     address = scrapy.Field()  #地址
14     types = scrapy.Field()    #學校類型(小學,中學,大學)

     2) 打開 mySpider/spiders目錄里的 __init__.py寫邏輯 ,直接上程式碼,有注釋

 1 import scrapy
 2 import json
 3 from urllib.parse import urlencode
 4 from .. import items
 5 class DmozSpider(scrapy.Spider):
 6     name = "map"
 7     allowed_domains = []
 8     #三層循環數組分別請求api,由於百度api返回的數據不是所有,所以必須傳入頁碼,來爬取更多數據。
10     def start_requests(self):
11         cities = ['北京','上海','深圳']14         types =['小學','中學','大學']
15         for city in cities:
16             for page in range(1, 16):
17                 for type_one in types:
18                     base_url = '//api.map.baidu.com/place/v2/search?'
19                     params = {
20                         'query': type_one,
21                         'region': city,
22                         'output':'json',
23                         'ak': '你的ak',
25                         'page_num': page
26                     }
27                     url = base_url + urlencode(params)
28                     yield scrapy.Request(url, callback=self.parse,meta={"types":type_one})
29 
30     def parse(self, response):
31         res = json.loads(response.text) #請求回來數據需轉成json
32         result= res.get('results')
33         types = response.meta["types"]  #由於api返回來數據沒有學校type的數據,這裡需要自己接一下 傳參時的type參數
34         #print(types)
35         if result:
36             for result_one in result:
37                 item = items.GetpointItem() #調用item的GetpointItem類,導出item
38                 item['name'] = result_one.get('name')
39                 item['lat'] = result_one.get('location').get('lat')
40                 item['lng'] = result_one.get('location').get('lng')42                 item['city'] = result_one.get('city')
43                 item['area'] = result_one.get('area')
44                 item['types'] = types
45                 item['address'] = result_one.get('address')
46                 yield item
47         else:
48              print('網路請求錯誤')

  3)item導出來了,數據獲取到了,然後 入庫,打開pipelines.py ,程式碼如下:

from itemadapter import ItemAdapter
import pymysql
import json

class DBPipeline(object):
    def __init__(self):
        # 連接MySQL資料庫
        self.connect=pymysql.connect(host='localhost',user='root',password='1q2w3e',db='mapspider',port=3306)
        self.cursor=self.connect.cursor()
    def process_item(self, item, spider):
        # 往資料庫裡面寫入數據
        try:
            self.cursor.execute("""select * from school where name = %s""", item['name'])
            ret = self.cursor.fetchone()
            if ret:
                print(item['name']+'***********數據重複!***************')
            else:
                self.cursor.execute(
                """insert into school(name, lng, lat, type,city,county,address)
                value (%s, %s, %s, %s, %s, %s, %s)""",
                (
                 item['name'],
                 json.dumps(item['lng']),
                 json.dumps(item['lat']),
                 item['types'],
                 item['city'],
                 item['area'],
                 item['address']
                 ))
                self.connect.commit()
                return item
        except Exception as eror:
            print('錯誤')
    # 關閉資料庫
    def close_spider(self,spider):
        self.cursor.close()
        self.connect.close()

重複數據的話,fecthOne直接排除 ,入庫。。。。,

4)執行腳本 scray crawl map

scrapy crawl map

name 要寫對哦

回車 ,開始 唰唰唰

 

成果如下:

    

     期間 ,百度地圖 api 多次並發,不讓訪問了,多爬幾次就好了,程式邏輯 曉得就好了。

 介面api爬完了,下次爬一爬 頁面xpath上的內容。