Selenium+PhantomJS替代方案


 

問題描述:

 

python3在使用selenium+PhantomJS動態抓取網頁時,出現如下報錯信息:

 

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

 

翻譯過來就是:selenium已經放棄PhantomJS了,建議使用火狐或者谷歌無界面瀏覽器。

so,PhantomJS要退出歷史舞台了。

 

解決方案:

selenium版本降級(不推薦)

通過pip show selenium顯示,默認安裝版本為3.8.1。

將其卸載pip uninstall selenium,重新安裝並指定版本號pip install selenium==2.48.0。

再次運行,發現沒有報錯。

 

使用無界面瀏覽器

Selenium+Headless Firefox

Selenium+Headless Firefox和Selenium+Firefox,區別就是實例option的時候設置-headless參數。

 

前提條件:

- 本地安裝Firefox瀏覽器

- 本地需要geckodriver驅動器文件,如果不配置環境變量的話,需要手動指定executable_path參數。

 

示例代碼:

 

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.baidu.com/")
    print(driver.page_source)
    driver.close()

if __name__ == '__main__':
    main()

 

Selenium+Headless Chrome

 

前提條件:

- 本地安裝Chrome瀏覽器

- 本地需要chromedriver驅動器文件,如果不配置環境變量的話,需要手動指定executable_path參數。

 

示例:

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()

 

 

python selenium模塊使用出錯,找不到路徑

 

selenium.common.exceptions.WebDriverException: Message: 'geckodriver' executable needs to be in PATH.

 

Windows環境下:

1、下載geckodriver.exe:

地址:https://github.com/mozilla/geckodriver/releases

請根據系統版本選擇下載;(如Windows 64位系統)

2、下載解壓后將getckodriver.exe復制到Firefox的安裝目錄下,如(C:\Program Files\Mozilla Firefox),並在環境變量Path中添加路徑:C:\Program Files\Mozilla Firefox;

3.重啟cmd或IDLE再次運行代碼即可

 

ubuntu16.04環境下

1、下載 geckodriverckod

地址: https://github.com/mozilla/geckodriver/releases

2、解壓后將geckodriverckod 存放至 /usr/local/bin/ 路徑下即可

 

 

參考鏈接:

https://blog.csdn.net/liu5257/article/details/53437878

https://blog.csdn.net/u010358168/article/details/79749149


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM