基于Python+Selenium+Chrome headless 模式入門

1. 概述

基于Python, Selenium, Chrome headless (無頭瀏覽器) 訪問頁面, 并將內(nèi)容保存到本地文件.

初步干了一次爬數(shù)據(jù)的工作,寫一寫入門的心得.分享一下,不足之處未來逐步完善.

2. 環(huán)境準(zhǔn)備

Python 3.6.5?

? ? 注:這個(gè)附帶的工具 IDLE (Python 3.6 64-bit) 調(diào)試很方便.按F5就行了

Selenium 2.0?

????注: 需要帶 WebDriver?

Chrome 59以上版本可以運(yùn)行Headless模式

3. 代碼實(shí)例

主要功能與步驟

1) 使用chrome headless 模式打開頁面

2) 根據(jù)頁面標(biāo)簽,利用Selenium 定位需要查找和分析頁面相關(guān)內(nèi)容

3) 將有用的功能,寫入指定文件

廢話不多直接上代碼

# 引入休眠等待庫

import time

# 引入selenium的瀏覽器驅(qū)動接口

from selenium import webdriver

# 引入chrome選項(xiàng)

from selenium.webdriver.chrome.options import Options

# 配置chrome瀏覽器(無頭模式)

chrome_options = Options()

chrome_options.add_argument('--headless')

driver = webdriver.Chrome(chrome_options=chrome_options)

# 沒有寫錯(cuò),就是要頁面夠長.不然頁面內(nèi)容會點(diǎn)不到 (第一個(gè)坑)

driver.set_window_size(1024, 7680)

# 加載頁面

driver.get("https://www.example.com")

# 這里進(jìn)行嵌套,模擬點(diǎn)擊打開詳細(xì)頁,可以抓取詳細(xì)內(nèi)容

for i in range(1,21):

??? # 根據(jù)css中的class查找對應(yīng)的element 集合

? ? counts = len(driver.find_elements_by_css_selector(".item_con_list .position_link"))

? ? print ("第" + str(i) + "頁,本頁共有:" + str(counts) + "條記錄")

? ? for j in range(counts):

? ? ? ? # 新開一個(gè)窗口

? ? ? ? url = driver.find_elements_by_css_selector(".item_con_list .position_link")[j]

? ? ? ? print('? 跳轉(zhuǎn)第' + str(j) + "條:" + url.get_attribute("href"))

? ? ? ? url.click()

? ? ? ? time.sleep(1)

? ? ? ? # 獲取當(dāng)前窗口句柄集合

? ? ? ? handles = driver.window_handles

? ? ? ? # 切換窗口

? ? ? ? for handle in handles:

? ? ? ? ? ? if handle!=driver.current_window_handle:

? ? ? ? ? ? ? ? driver.switch_to_window(handle)

? ? ? ? ? ? ? ? # 找到內(nèi)容

? ? ? ? ? ? ? ? try:

? ? ? ? ? ? ? ? ? ? data = driver.find_element_by_class_name("job_bt").text

? ? ? ? ? ? ? ? except:

? ? ? ? ? ? ? ? ? ? print("這個(gè)頁面沒拿到內(nèi)容")

? ? ? ? ? ? ? ? ? ? driver.save_screenshot(i+str(j)+".png")

??????????????? # 寫入內(nèi)容 ,要保持編碼一致,不然會出現(xiàn)保存出錯(cuò) (第二個(gè)坑)

? ? ? ? ? ? ? ? fileObject = open('example.txt', 'a', encoding='utf-8')

? ? ? ? ? ? ? ? fileObject.write(data)?

? ? ? ? ? ? ? ? fileObject.write('\n')?

? ? ? ? ? ? ? ? fileObject.close()

? ? ? ? ? ? ? ? break

? ? ? ? #關(guān)閉當(dāng)前窗口? ?

? ? ? ? driver.close()

? ? ? ? #切換(主)窗口

? ? ? ? driver.switch_to_window(handles[0])

? ? ? ? time.sleep(1)

? ? ? ? #生成當(dāng)前頁面快照,調(diào)試用的

? ? ? ? driver.save_screenshot("current.png")

? ? # 跳轉(zhuǎn)到下一頁

? ? driver.find_element_by_class_name("pager_next").click()

? ? print("跳轉(zhuǎn)到下一頁")

? ? time.sleep(5)

# 關(guān)閉瀏覽器

driver.quit()

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容