-
實現步驟
- 創建爬蟲項目
- 根據需求定義數據模型
- 實現爬蟲
- 保存爬取的數據
- 實現隨機user-agent和代理ip下載器中間件,解決ip反爬
-
實現爬蟲的具體步驟
- url url = 'https://sp0.baidu.com/8aQDcjqpAAV3otqbppnN2DJv/api.php?resource_id=6899&pn=20&rn=10&ie=utf-8&oe=utf-8&query=失信被執行人'
- 測試,如果不成功,可能是需要設置請求頭
- 請求方式 get
- 參數
- 請求頭 user-agent referer
- 返回數據個數
- 如何翻頁
- 有時候不用獲取url翻頁,根據請求中的翻頁參數,可以for循環請求
- url url = 'https://sp0.baidu.com/8aQDcjqpAAV3otqbppnN2DJv/api.php?resource_id=6899&pn=20&rn=10&ie=utf-8&oe=utf-8&query=失信被執行人'
-
保存失信名單信息
-
創建數據庫,創建表
-
在settings中配置數據庫信息
- host、port、db、user、password
-
實現管道類
-
在open_spider中,建立數據庫連接,獲取cursor
-
def open_spider(self, spider): """不用做判斷,因為三只爬蟲的爬取結果全部放到同一個數據庫里邊""" # 創建數據庫連接 self.connection = pymysql.connect(host=MYSQL_HOST, port=MYSQL_PORT, db=MYSQL_DB, user=MYSQL_USER, password=MYSQL_PASSWORD) # 獲取游標 self.cursor = self.connection.cursor()
-
-
在close_spider中,關閉cursor,關閉數據庫連接
-
def close_spider(self, spider): # 關閉游標 self.cursor.close() # 關閉連接 self.connection.close()
-
-
在process_item中,如果數據不存在,保存數據
-
def process_item(self, item, spider): # 存儲過程,最重要是判斷數據是否已經存在 # 判斷數據是否已經存在 if item['age'] == 0: select_count_sql = "select count(1) from dishonest where name='{}' and area='{}'".format(item['name'], item['area']) else: select_count_sql = "select count(1) from dishonest where card_num='{}'".format(item['card_num']) # 執行查詢 self.cursor.execute(select_count_sql) count = self.cursor.fetchone()[0] # 游標會獲取的結果是列表形式 # 根據查詢結果,決定是否插入數據 if count == 0: keys, values = zip(*dict(item).items()) insert_sql = 'insert into dishonest ({}) values ({})'.format( ','.join(keys), ','.join(['%s']*len(values)) ) self.cursor.execute(insert_sql,values) self.connection.commit() spider.logger.info('插入數據') else: spider.logger.info('數據重復')
-
-
-
在settings.py中開啟管道
-
-
實現隨機User-Agent下載器中間件
-
准備User-Agent列表
-
定義RandomUserAgent類
-
實現process_request方法,設置隨機的User_Agent
class RandomUserAgent(object): def process_request(self, request, spider): request.headers['User-Agent'] = random.choice(USER_AGENTS) return None
-
-
實現代理ip下載器中間件
-
定義ProxyMiddleware類
class RandomUserAgent(object): def process_request(self, request, spider): request.headers['User-Agent'] = random.choice(USER_AGENTS) return None
-
實現proecss_request方法,設置代理ip
class ProxyMiddleware(object): def process_request(self, request, spider): # 設置代理ip # 1. 獲取請求的協議頭 protocol = request.url.split('://')[0] # 2. 構建代理ip請求的url,從代理池獲取隨機的代理ip proxy_url = 'http://localhost:16888/random?protocol={}'.format(protocol) # 3. 發送請求,獲取代理ip response = requests.get(proxy_url) # 4. 把代理ip設置給request.meta['proxy'] request.meta['proxy'] = response.content.decode() return None
-
pycharm的全局搜索---雙擊shift
# settings文件中設置下載器中間件 DOWNLOADER_MIDDLEWARES = { 'dishonest.middlewares.RandomUserAgent': 543, 'dishonest.middlewares.ProxyMiddleware': 500, } 注意: # from scrapy.downloadermiddlewares.httpproxy import HttpProxyMiddleware ProxyMiddleware的數據需要注意,要小於750. # 750的來歷: 全局搜索HTTPPROXY_ENABLED,其所在文件中有 'scrapy.downloadermiddlewares.httpproxy.HttpProxyMiddleware': 750,
-
-
設置重試次數
# 設置重試次數 RETRY_TIMES = 5 # 加上初始化那一次,共6次
-
settings文件中設置日志級別
# 配置日志等級 LOG_LEVEL = 'INFO'