您的位置:首頁技術文章
文章詳情頁

python+selenium+chromedriver實現爬蟲示例代碼

瀏覽:7日期:2022-07-30 14:23:35

下載好所需程序

1.Selenium簡介

Selenium是一個用于Web應用程序測試的工具,直接運行在瀏覽器中,就像真正的用戶在操作一樣。

2.Selenium安裝

方法一:在Windows命令行(cmd)輸入pip install selenium即可自動安裝,安裝完成后,輸入pip show selenium可查看當前的版本

python+selenium+chromedriver實現爬蟲示例代碼

方法二:直接下載selenium包:

selenium下載網址

Pychome安裝selenium如果出現無法安裝,參考以下博客解決Pycharm無法使用已經安裝Selenium的問題

3.禁止谷歌瀏覽器自動更新

搜索本地:管理工具-服務-Google自動更新服務-選擇禁止

python+selenium+chromedriver實現爬蟲示例代碼

安裝瀏覽器對應的驅動driver我這里用的是谷歌,選擇對應的驅動版本

驅動的下載地址如下:

http://chromedriver.storage.googleapis.com/index.html

python+selenium+chromedriver實現爬蟲示例代碼

python+selenium+chromedriver實現爬蟲示例代碼

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 webdriverbrowser=webdriver.Chrome()#打開瀏覽器url='https://news.qq.com/zt2020/page/feiyan.htm#/global?nojump=1'#獲取數據的地址#請求瀏覽器內容:請求方式:get,post,tokenbrowser.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 爬蟲內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!

標簽: Python 編程
相關文章:
国产综合久久一区二区三区