Selenium最新版本不再支持PhantomJS

今天想對(duì)《自動(dòng)讀取單位某系統(tǒng)數(shù)據(jù)》一文中的項(xiàng)目做些優(yōu)化,將Selenium+firefox改為無(wú)界面的PhantomJS,出現(xiàn)如下錯(cuò)誤:

UserWarning: Selenium support for PhantomJS has been deprecated, please use headless versions of Chrome or Firefox instead
  warnings.warn('Selenium support for PhantomJS has been deprecated, please use headless '

百度:意思是說(shuō)Selenium不再支持PhantomJS,請(qǐng)用無(wú)界面版本的chrome或firefox代替。

  • 完美解決方法轉(zhuǎn)發(fā)自這個(gè)博客:Selenium+PhantomJS使用時(shí)報(bào)錯(cuò)原因及解決方案
  • 在使用webdriver驅(qū)動(dòng)器文件時(shí),建議還是將其解壓至某個(gè)目錄,再手動(dòng)指定executable_path參數(shù),省得去設(shè)置環(huán)境參數(shù)(主要是因?yàn)槲业膍ac里設(shè)置后總是不能用)。

使用無(wú)界面瀏覽器

Selenium+Headless Firefox

Selenium+Headless FirefoxSelenium+Firefox,區(qū)別就是實(shí)例option的時(shí)候設(shè)置-headless參數(shù)。

前提條件:

  • 本地安裝Firefox瀏覽器
  • 本地需要geckodriver驅(qū)動(dòng)器文件,如果不配置環(huán)境變量的話,需要手動(dòng)指定executable_path參數(shù)。

示例代碼:

from selenium.webdriver import Firefox
from selenium.webdriver.firefox.options import Options


def main():
    options = Options()
    options.add_argument('-headless')
    driver = Firefox(executable_path='./geckodriver', firefox_options=options)
    driver.get("https://www.qiushibaike.com/8hr/page/1/")
    print(driver.page_source)
    driver.close()


if __name__ == '__main__':
    main()
Selenium+Headless Chrome

Firefox類(lèi)似,雙手奉上。

前提條件:

  • 本地安裝Chrome瀏覽器
  • 本地需要chromedriver驅(qū)動(dòng)器文件,如果不配置環(huán)境變量的話,需要手動(dòng)指定executable_path參數(shù)。

示例:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options


def main():
    chrome_options = Options()
    chrome_options.add_argument('--headless')
    chrome_options.add_argument('--disable-gpu')
    driver = webdriver.Chrome(executable_path='./chromedriver', chrome_options=chrome_options)
    driver.get("https://www.baidu.com")
    print(driver.page_source)
    driver.close()


if __name__ == '__main__':
    main()

如果本文對(duì)您有幫助,請(qǐng)給我留個(gè)言。謝謝!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容