利用selenium+requests訪問頁面爬取拉勾網(wǎng)招聘信息
觀察頁面可知,頁面數(shù)據(jù)屬于動態(tài)加載 所以現(xiàn)在我們通過抓包工具,獲取數(shù)據(jù)包
觀察其url和參數(shù)
url="https://www.lagou.com/jobs/positionAjax.json?px=defaultneedAddtionalResult=false" 參數(shù): city=%E5%8C%97%E4%BA%AC ==》城市 first=true ==》無用 pn=1 ==》頁數(shù) kd=%E6%95%B0%E6%8D%AE%E5%88%86%E6%9E%90 ==》商品關(guān)鍵詞
所以我們要想實現(xiàn)全站爬取,需要有city和頁數(shù)
我們打開拉勾網(wǎng),觀察后發(fā)現(xiàn),他的數(shù)據(jù)并不是完全展示的,比如說 在城市篩選選擇全國 僅僅只顯示30頁 但總頁數(shù)是遠遠大于30頁的;我又選擇北京發(fā)現(xiàn)是30頁又選擇北京下的海淀區(qū)又是30頁,可能我們無法把數(shù)據(jù)全部的爬取,但我們可以盡可能的將數(shù)據(jù)多的爬取
我們?yōu)榱双@取全站數(shù)據(jù),必然離不開的有兩個參數(shù) 一個是城市一個是頁數(shù),所以我們利用selenium自動化去獲取所有城市和對應(yīng)頁數(shù)
def City_Page(self): City_Page={} url="https://www.lagou.com/jobs/allCity.html?keyword=%spx=defaultcompanyNum=0isCompanySelected=falselabelWords="%(self.keyword) self.bro.get(url=url) sleep(30) print("開始獲取城市及其最大頁數(shù)") if "驗證系統(tǒng)" in self.bro.page_source: sleep(40) html = etree.HTML(self.bro.page_source) city_urls = html.xpath('//table[@class="word_list"]//li/input/@value') for city_url in city_urls: try: self.bro.get(city_url) if "驗證系統(tǒng)" in self.bro.page_source: sleep(40) city=self.bro.find_element_by_xpath('//a[@class="current_city current"]').text page=self.bro.find_element_by_xpath('//span[@class="span totalNum"]').text City_Page[city]=page sleep(0.5) except: pass self.bro.quit() data = json.dumps(City_Page) with open("city_page.json", 'w', encoding="utf-8")as f: f.write(data) return City_Page
我們有了每個城市對應(yīng)的最大頁數(shù),就可以生成訪問頁面所需的參數(shù)
def Params_List(self): with open("city_page.json", "r")as f: data = json.loads(f.read()) Params_List = [] for a, b in zip(data.keys(), data.values()): for i in range(1, int(b) + 1): params = { 'city': a, 'pn': i, 'kd': self.keyword } Params_List.append(params) return Params_List
最后我們可以通過添加請求頭和使用params url來訪問頁面獲取數(shù)據(jù)
def Parse_Data(self,params): url = "https://www.lagou.com/jobs/positionAjax.json?needAddtionalResult=false" header={ 'referer': 'https://www.lagou.com/jobs/list_%E6%95%B0%E6%8D%AE%E5%88%86%E6%9E%90?labelWords=fromSearch=truesuginput=', 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36', 'cookie':'' } try: text = requests.get(url=url, headers=header, params=params).text if "頻繁" in text: print("操作頻繁,已被發(fā)現(xiàn) 當前為第%d個params"%(i)) data=json.loads(text) result=data["content"]["positionResult"]["result"] for res in result: with open(".//lagou1.csv", "a",encoding="utf-8") as f: writer = csv.DictWriter(f, res.keys()) writer.writerow(res) sleep(1) except Exception as e: print(e) pass
盡管數(shù)據(jù)只顯示前30頁,但數(shù)據(jù)還是未完全獲取
在利用selenium獲取城市最大頁數(shù)時 應(yīng)手動登錄拉勾網(wǎng),并且其在訪問過程中可能會出現(xiàn)驗證系統(tǒng)需要驗證
利用requests訪問頁面獲取數(shù)據(jù)時 盡量sleep時間長一點,操作頻繁會封IP
到此這篇關(guān)于python爬蟲之利用Selenium+Requests爬取拉勾網(wǎng)的文章就介紹到這了,更多相關(guān)Selenium+Requests爬取拉勾網(wǎng)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!