python+selenium+chromedriver實現爬蟲示例程式碼
下載好所需程式
1.Selenium簡介
Selenium是一個用於Web應用程式測試的工具,直接執行在瀏覽器中,就像真正的使用者在操作一樣。
2.Selenium安裝
方法一:在Windows命令列(cmd)輸入pip install selenium即可自動安裝,安裝完成後,輸入pip show selenium可檢視當前的版本
方法二:直接下載selenium包:
selenium下載網址
Pychome安裝selenium如果出現無法安裝,參考以下部落格
解決Pycharm無法使用已經安裝Selenium的問題
3.禁止谷歌瀏覽器自動更新
搜尋本地:管理工具-服務-Google自動更新服務-選擇禁止
安裝瀏覽器對應的驅動driver
我這裡用的是谷歌,選擇對應的驅動版本
驅動的下載地址如下:
http://chromedriver.storage.googleapis.com/index.html
win32、win64的都下載win32.zip的
將下載的chromedriver進行解壓,並將檔案複製或移動到,瀏覽器快捷方式所在目錄。
環境變數配置
1.Python環境配置
2.chromedriver環境配置
3.pychrome的python環境指向自己電腦安裝好的python
注意:將下載好的chromewebdriver.exe驅動放在Python的安裝路徑下的Scripts裡面,同時將Scripts路徑新增到PATH中,這樣每次執行python的時候就會自動載入驅動
程式碼實現
#已經準備環境:webdriver:Google已經安裝好;環境變數配置好;pip install selenium; #selenium是一個包,包有很多物件,物件有屬性,方法。 from selenium import webdriver browser=webdriver.Chrome()#開啟瀏覽器 url="https://news.qq.com/zt2020/page/feiyan.htm#/global?nojump=1"#獲取資料的地址 #請求瀏覽器內容:請求方式:get,post,token browser.get(url) #css選擇器,id選擇器:#開頭,class選擇器:.開頭,標籤選擇器:p,span,div。 coronavirus_countent=browser.find_element_by_class_name('d')#定位到class選擇器d這個內容 print(coronavirus_countent)#檢視內容,session,一種快取機制,通過瀏覽器解析,然後快取的內容 # <selenium.webdriver.remote.webelement.WebElement (session="a1aa22161543b44f599e97b35dbc1ac5",element="fe645993-43cb-46cf-83a7-2488dd3d838a")> print(coronavirus_countent.text)#檢視當前css.class中的d的內容 coronavirus_time=browser.find_element_by_class_name('ml')#定位到class選擇器d這個內容 print(coronavirus_time.text) coronavirus_data=browser.find_element_by_class_name('nowConfirm')#定位到class選擇器d這個內容 print("=======") print(coronavirus_data.text) print("=====找nowConfirm下面的字內容") coronavirus_sub=coronavirus_data.find_element_by_class_name('addnum') print(coronavirus_sub.text) browser.quit()
到此這篇關於python+selenium+chromedriver實現爬蟲示例程式碼的文章就介紹到這了,更多相關python selenium chromedriver 爬蟲內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!