目標url:https://www.lagou.com/
用selenium爬蟲實現,輸入任意關鍵字,比如 python 數據分析,點擊搜索,得到的有關崗位信息,爬取下來保存到Excel。
有30頁,每個頁面有15條招聘信息。
from selenium import webdriverimport timeimport loggingimport randomimport openpyxlwb = openpyxl.Workbook()sheet = wb.activesheet.append([&39;, &39;, &39;,&39;, &39;, &39;,&39;,&39;])logging.basicConfig(level=logging.INFO, format=&39;)def search_product(key_word): browser.find_element_by_id(&39;).click() 39;search_input& 定位搜索框 輸入關鍵字 browser.find_element_by_class_name(&39;).click() 最大化窗口 time.sleep(2) browser.find_element_by_class_name(&39;).click() 34;scroll(0,3000)& 下拉滾動條 get_data() 模擬點擊下一頁 翻頁爬取數據 每爬取一頁數據 休眠 控制抓取速度 防止被反爬 讓輸驗證碼 for i in range(29): browser.find_element_by_class_name(&39;).click() time.sleep(1) browser.execute_script(&34;) get_data() time.sleep(random.randint(3, 5))def get_data(): items = browser.find_elements_by_xpath(&34;s_position_list&39;) for item in items: job_name = item.find_element_by_xpath(&34;p_top&39;).text company_name = item.find_element_by_xpath(&34;company_name&39;).text city = item.find_element_by_xpath(&34;p_top&34;add&39;).text industry = item.find_element_by_xpath(&34;industry&39;).text salary = item.find_element_by_xpath(&34;money&39;).text experience_edu = item.find_element_by_xpath(&34;p_bot&34;li_b_l&39;).text welfare = item.find_element_by_xpath(&34;li_b_r&39;).text job_label = item.find_element_by_xpath(&34;list_item_bot&34;li_b_l&39;).text data = f&39; logging.info(data) sheet.append([job_name, company_name, city,industry, salary, experience_edu, welfare, job_label])def main(): browser.get(&39;) time.sleep(random.randint(1, 3)) search_product(keyword) wb.save(&39;)if __name__ == &39;: keyword = &39; 39;D:\python\pycharm2020\chromedriver.exe& 關閉左上方 Chrome 正受到自動測試軟體的控制的提示 options.add_experimental_option(&39;, False) options.add_experimental_option(&34;, [&39;]) browser = webdriver.Chrome(options=options, executable_path=chrome_driver) main() browser.quit()
爬蟲運行,成功爬取數據並保存到Excel,運行結果如下: