【Python3爬蟲】拉勾網爬蟲
阿新 • • 發佈:2018-11-14
一、思路分析:
在之前寫拉勾網的爬蟲的時候,總是得到下面這個結果(真是頭疼),當你看到下面這個結果的時候,也就意味著被反爬了,因為一些網站會有相應的反爬蟲措施,例如很多網站會檢測某一段時間某個IP的訪問次數,如果訪問頻率太快以至於看起來不像正常訪客,它可能就會禁止這個IP的訪問:
對於拉勾網,我們要找到職位資訊的ajax介面倒是不難(如下圖),問題是怎麼不得到上面的結果。
要想我們的爬蟲不被檢測出來,我們可以使用代理IP,而網上有很多提供免費代理的網站,比如西刺代理、快代理、89免費代理等等,我們可以爬取一些免費的代理然後搭建我們的代理池,使用的時候直接從裡面進行呼叫就好了。
二、主要程式碼:
proxies.py(爬取免費代理並驗證其可用性,然後生成代理池)
1 import requests 2 import re 3 4 5 class Proxies: 6 def __init__(self): 7 self.proxy_list = []8 self.headers = { 9 "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) " 10 "Chrome/45.0.2454.101 Safari/537.36", 11 'Accept-Encoding': 'gzip, deflate, sdch', 12 } 13 14 # 爬取西刺代理的國內高匿代理 15 defget_proxy_nn(self): 16 proxy_list = [] 17 res = requests.get("http://www.xicidaili.com/nn", headers=self.headers) 18 ip_list = re.findall('<td>(\d+\.\d+\.\d+\.\d+)</td>', res.text) 19 port_list = re.findall('<td>(\d+)</td>', res.text) 20 for ip, port in zip(ip_list, port_list): 21 proxy_list.append(ip + ":" + port) 22 return proxy_list 23 24 # 驗證代理是否能用 25 def verify_proxy(self, proxy_list): 26 for proxy in proxy_list: 27 proxies = { 28 "http": proxy 29 } 30 try: 31 if requests.get('http://www.baidu.com', proxies=proxies, timeout=2).status_code == 200: 32 print('success %s' % proxy) 33 if proxy not in self.proxy_list: 34 self.proxy_list.append(proxy) 35 except: 36 print('fail %s' % proxy) 37 38 # 儲存到proxies.txt裡 39 def save_proxy(self): 40 # 驗證代理池中的IP是否可用 41 print("開始清洗代理池...") 42 with open("proxies.txt", 'r', encoding="utf-8") as f: 43 txt = f.read() 44 # 判斷代理池是否為空 45 if txt != '': 46 self.verify_proxy(txt.strip().split('\n')) 47 else: 48 print("代理池為空!\n") 49 print("開始存入代理池...") 50 # 把可用的代理新增到代理池中 51 with open("proxies.txt", 'w', encoding="utf-8") as f: 52 for proxy in self.proxy_list: 53 f.write(proxy + "\n") 54 55 56 if __name__ == '__main__': 57 p = Proxies() 58 results = p.get_proxy_nn() 59 print("爬取到的代理數量", len(results)) 60 print("開始驗證:") 61 p.verify_proxy(results) 62 print("驗證完畢:") 63 print("可用代理數量:", len(p.proxy_list)) 64 p.save_proxy()
在middlewares.py中新增如下程式碼:
1 class LaGouProxyMiddleWare(object): 2 def process_request(self, request, spider): 3 import random 4 import requests 5 with open("具體路徑\proxies.txt", 'r', encoding="utf-8") as f: 6 txt = f.read() 7 proxy = "" 8 flag = 0 9 for i in range(10): 10 proxy = random.choice(txt.split('\n')) 11 proxies = { 12 "http": proxy 13 } 14 if requests.get('http://www.baidu.com', proxies=proxies, timeout=2).status_code == 200: 15 flag = 1 16 break 17 if proxy != "" and flag: 18 print("Request proxy is {}".format(proxy)) 19 request.meta["proxy"] = "http://" + proxy 20 else: 21 print("沒有可用的IP!")
然後還要在settings.py中新增如下程式碼,這樣就能使用代理IP了:
1 SPIDER_MIDDLEWARES = { 2 'LaGou.middlewares.LaGouProxyMiddleWare': 543, 3 }
在item.py中新增如下程式碼:
1 import scrapy 2 3 4 class LaGouItem(scrapy.Item): 5 city = scrapy.Field() # 城市 6 salary = scrapy.Field() # 薪水 7 position = scrapy.Field() # 職位 8 education = scrapy.Field() # 學歷要求 9 company_name = scrapy.Field() # 公司名稱 10 company_size = scrapy.Field() # 公司規模 11 finance_stage = scrapy.Field() # 融資階段
在pipeline.py中新增如下程式碼:
1 import pymongo 2 3 4 class LaGouPipeline(object): 5 def __init__(self): 6 conn = pymongo.MongoClient(host="127.0.0.1", port=27017) 7 self.col = conn['Spider'].LaGou 8 9 def process_item(self, item, spider): 10 self.col.insert(dict(item)) 11 return item
在spiders資料夾下新建一個spider.py,程式碼如下:
1 import json 2 import scrapy 3 import codecs 4 import requests 5 from time import sleep 6 from LaGou.items import LaGouItem 7 8 9 class LaGouSpider(scrapy.Spider): 10 name = "LaGouSpider" 11 12 def start_requests(self): 13 # city = input("請輸入城市:") 14 # position = input("請輸入職位方向:") 15 city = "上海" 16 position = "python" 17 url = "https://www.lagou.com/jobs/positionAjax.json?px=default&needAddtionalResult=false&city={}".format(city) 18 headers = { 19 "Referer": "https://www.lagou.com/jobs/list_{}?city={}&cl=false&fromSearch=true&labelWords=&suginput=".format(codecs.encode(position, 'utf-8'), codecs.encode(city, 'utf-8')), 20 "Cookie": "_ga=GA1.2.2138387296.1533785827; user_trace_token=20180809113708-7e257026-9b85-11e8-b9bb-525400f775ce; LGUID=20180809113708-7e25732e-9b85-11e8-b9bb-525400f775ce; index_location_city=%E6%AD%A6%E6%B1%89; LGSID=20180818204040-ea6a6ba4-a2e3-11e8-a9f6-5254005c3644; JSESSIONID=ABAAABAAAGFABEFFF09D504261EB56E3CCC780FB4358A5E; Hm_lvt_4233e74dff0ae5bd0a3d81c6ccf756e6=1534294825,1534596041,1534596389,1534597802; TG-TRACK-CODE=search_code; Hm_lpvt_4233e74dff0ae5bd0a3d81c6ccf756e6=1534599373; LGRID=20180818213613-acc3ccc9-a2eb-11e8-9251-525400f775ce; SEARCH_ID=f20ec0fa318244f7bcc0dd981f43d5fe", 21 "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.89 Safari/537.36" 22 } 23 data = { 24 "first": "true", 25 "pn": 1, 26 "kd": position 27 } 28 res = requests.post(url, headers=headers, data=data) 29 # 獲取相關職位結果數目 30 count = res.json()['content']['positionResult']['totalCount'] 31 # 由於最多顯示30頁,也就是最多顯示450條職位資訊 32 page_count = count // 15 + 1 if count <= 450 else 30 33 for i in range(page_count): 34 sleep(5) 35 yield scrapy.FormRequest( 36 url=url, 37 formdata={ 38 "first": "true", 39 "pn": str(i + 1), 40 "kd": position 41 }, 42 callback=self.parse 43 ) 44 45 def parse(self, response): 46 try: 47 # 解碼並轉成json格式 48 js = json.loads(response.body.decode('utf-8')) 49 result = js['content']['positionResult']['result'] 50 item = LaGouItem() 51 for i in result: 52 item['city'] = i['city'] 53 item['salary'] = i['salary'] 54 item['position'] = i['positionName'] 55 item['education'] = i['education'] 56 item['company_name'] = i['companyFullName'] 57 item['company_size'] = i['companySize'] 58 item['finance_stage'] = i['financeStage'] 59 yield item 60 except: 61 print(response.body)
三、執行結果:
由於使用的是免費代理,短時間內就失效了,所以會碰上爬取不到資料的情況,所以推薦使用付費代理。
完整程式碼已上傳到GitHub:https://github.com/QAQ112233/LaGou