久久r热视频,国产午夜精品一区二区三区视频,亚洲精品自拍偷拍,欧美日韩精品二区

您的位置:首頁技術(shù)文章
文章詳情頁

Python使用Selenium自動進行百度搜索的實現(xiàn)

瀏覽:140日期:2022-06-14 15:13:46
目錄安裝 Selenium寫代碼點位網(wǎng)頁元素

我們今天介紹一個非常適合新手的python自動化小項目,項目雖小,但是五臟俱全。它是一個自動化操作網(wǎng)頁瀏覽器的小應用:打開瀏覽器,進入百度網(wǎng)頁,搜索關鍵詞,最后把搜索結(jié)果保存到一個文件里。這個例子非常適合新手學習Python網(wǎng)絡自動化,不僅能夠了解如何使用Selenium,而且還能知道一些超級好用的小工具。

當然有人把操作網(wǎng)頁,然后把網(wǎng)頁的關鍵內(nèi)容保存下來的應用一律稱作網(wǎng)絡爬蟲,好吧,如果你想這么爬取內(nèi)容,隨你。但是,我更愿意稱它為網(wǎng)絡機器人。

我今天介紹的項目使用Selenium,Selenium 是支持 web 瀏覽器自動化的一系列工具和庫的綜合項目。Selenium 的核心是 WebDriver,這是一個編寫指令集的接口,可以在許多瀏覽器中互換運行。

閑言少敘,硬貨安排。

安裝 Selenium

可以使用 pip 安裝 Python 的 Selenium 庫:pip install selenium

(可選項:要執(zhí)行項目并控制瀏覽器,需要安裝特定于瀏覽器的 WebDriver 二進制文件。

下載 WebDriver 二進制文件 并放入 系統(tǒng) PATH 環(huán)境變量 中.)

由于本地瀏覽器版本升級,引起的版本不一致問題,和系統(tǒng)PATH環(huán)境變量的設置比較繁瑣,所以我使用webdriver_manager,

安裝 Install manager:

pip install webdriver-manager寫代碼

引入模塊:

from selenium import webdriverfrom webdriver_manager.chrome import ChromeDriverManagerfrom selenium.webdriver.common.by import Byfrom selenium.webdriver.support.ui import WebDriverWaitfrom selenium.webdriver.support import expected_conditions as ECfrom selenium.webdriver.common.keys import Keys

首先我們定義一個類Search_Baidu, 它主要用于初始化;定義自動化步驟的方法;結(jié)束關閉瀏覽器。

class Search_Baidu:def __init__(self):def search(self, keyword):def tear_down(self):

接下來我們分別介紹每個方法的實現(xiàn)過程。

def __init__(self): #類構(gòu)造函數(shù),用于初始化selenium的webdriverurl = ’https://www.baidu.com/’ #這里定義訪問的網(wǎng)絡地址self.url = urloptions = webdriver.ChromeOptions()options.add_experimental_option('prefs', {'profile.managed_default_content_settings.images': 2}) # 不加載圖片,加快訪問速度options.add_experimental_option(’excludeSwitches’, [’enable-automation’]) # 此步驟很重要,設置為開發(fā)者模式,防止被各大網(wǎng)站識別出來使用了Selenium# 這里使用chrome瀏覽器,而且使用我們剛才安裝的webdriver_manager的chrome driver,并賦值上面的瀏覽器設置options變量self.browser = webdriver.Chrome(ChromeDriverManager().install(), options=options)self.wait = WebDriverWait(self.browser, 10) #超時時長為10s,由于自動化需要等待網(wǎng)頁控件的加載,所以這里設置一個默認的等待超時,時長為10秒 def tear_down(self):self.browser.close() #最后,關閉瀏覽器

接下來是重頭戲,寫我們操作瀏覽器的步驟,打開瀏覽器,進入百度網(wǎng)頁,輸入搜索關鍵字:Selenium,等待搜索結(jié)果,把搜索結(jié)果的題目和網(wǎng)址保存到文件里。

def search(self, keyword): # 打開百度網(wǎng)頁 self.browser.get(self.url) # 等待搜索框出現(xiàn),最多等待10秒,否則報超時錯誤 search_input = self.wait.until(EC.presence_of_element_located((By.XPATH, ’//*[@id='kw']’))) # 在搜索框輸入搜索的關鍵字 search_input.send_keys(keyword) # 回車 search_input.send_keys(Keys.ENTER) # 等待10秒鐘 self.browser.implicitly_wait(10) # 找到所有的搜索結(jié)果 results = self.browser.find_elements_by_css_selector('.t a , em , .c-title-text') # 遍歷所有的搜索結(jié)果 with open('search_result.txt','w') as file: for result in results: if result.get_attribute('href'):print(result.get_attribute('text').strip())# 搜索結(jié)果的標題title = result.get_attribute('text').strip()# 搜索結(jié)果的網(wǎng)址link = result.get_attribute('href')# 寫入文件file.write(f'Title: {title}, link is: {link} n')點位網(wǎng)頁元素

這里頭有個關鍵點,就是如何點位網(wǎng)頁元素:

比如:

search_input = self.wait.until(EC.presence_of_element_located((By.XPATH, ’//*[@id='kw']’)))

還有:

self.browser.find_elements_by_css_selector('.t a , em , .c-title-text')

打個比方,快遞員通過地址找到你家,給你送快遞,這里的XPATH和CSS Selector就是網(wǎng)頁元素的地址,那么如何得到呢?第一個就是Chrome自帶的開發(fā)者工具,可以快捷鍵F12,也可以自己在下圖中找到:

Python使用Selenium自動進行百度搜索的實現(xiàn)

然后在百度搜索框,右鍵:

Python使用Selenium自動進行百度搜索的實現(xiàn)

找到輸入框的HTML元素,

Python使用Selenium自動進行百度搜索的實現(xiàn)

在HTML元素右鍵,拷貝XPath地址。

Python使用Selenium自動進行百度搜索的實現(xiàn)

這是比較簡單的定位網(wǎng)頁元素的方法。接下來我們定位搜索結(jié)果元素的時候,就遇到了麻煩,如下圖:

Python使用Selenium自動進行百度搜索的實現(xiàn)

我們不能單獨的定位每個元素,而是要找到規(guī)律,一次把所有的搜索結(jié)果找到,然后返回一個list,我們好遍歷這個list,這個怎么實現(xiàn)呢?

接下來,我們請出一大神器:SelectorGadget

Python使用Selenium自動進行百度搜索的實現(xiàn)

SelectorGadget是一個CSS Selector生成器,大家可以在他的官方文檔找到具體的使用說明,我這里簡單介紹一下:首先啟動SelectorGadget,點擊一下圖標

Python使用Selenium自動進行百度搜索的實現(xiàn)

瀏覽器會出現(xiàn)下面的框框:

Python使用Selenium自動進行百度搜索的實現(xiàn)

然后我們在網(wǎng)頁用鼠標左鍵,點擊我們要定位的元素

Python使用Selenium自動進行百度搜索的實現(xiàn)

然后頁面會變成下面的樣子:

Python使用Selenium自動進行百度搜索的實現(xiàn)

所有黃色的部分說明都被選擇了,如果我們不想要的元素,右鍵點擊,使它變?yōu)榧t色,說明它被去掉了。如果沒有被選擇我們又需要的元素,我們左鍵選擇它,使它變?yōu)榫G色。最后我們希望選擇的頁面元素都變成了綠色或者黃色,如下圖:

Python使用Selenium自動進行百度搜索的實現(xiàn)

我們就可以拷貝框框里的內(nèi)容作為CSS Selector了。

Python使用Selenium自動進行百度搜索的實現(xiàn)

通過CSS Selector找到所有的搜索結(jié)果。

results = self.browser.find_elements_by_css_selector('.t a , em , .c-title-text')

到此,我們就實現(xiàn)了這么個簡單的小應用了,其實selenium就是幫助我們自動操作網(wǎng)頁元素,所以我們定位網(wǎng)頁元素就是重中之重,希望本文給你帶來一點幫助。

下面我附上代碼:

from datetime import timefrom selenium import webdriverfrom webdriver_manager.chrome import ChromeDriverManagerfrom selenium.webdriver.common.by import Byfrom selenium.webdriver.support.ui import WebDriverWaitfrom selenium.webdriver.support import expected_conditions as ECfrom selenium.webdriver.common.keys import Keysclass Search_Baidu: def __init__(self):url = ’https://www.baidu.com/’self.url = urloptions = webdriver.ChromeOptions()options.add_experimental_option('prefs', {'profile.managed_default_content_settings.images': 2}) # 不加載圖片,加快訪問速度options.add_experimental_option(’excludeSwitches’, [’enable-automation’]) # 此步驟很重要,設置為開發(fā)者模式,防止被各大網(wǎng)站識別出來使用了Seleniumself.browser = webdriver.Chrome(ChromeDriverManager().install(), options=options)self.wait = WebDriverWait(self.browser, 10) #超時時長為10s def search(self, keyword):# 打開百度網(wǎng)頁self.browser.get(self.url)# 等待搜索框出現(xiàn),最多等待10秒,否則報超時錯誤search_input = self.wait.until(EC.presence_of_element_located((By.XPATH, ’//*[@id='kw']’)))# 在搜索框輸入搜索的關鍵字search_input.send_keys(keyword)# 回車search_input.send_keys(Keys.ENTER)# 等待10秒鐘self.browser.implicitly_wait(10)# 找到所有的搜索結(jié)果results = self.browser.find_elements_by_css_selector('.t a , em , .c-title-text')# 遍歷所有的搜索結(jié)果with open('search_result.txt','w') as file:for result in results:if result.get_attribute('href'): print(result.get_attribute('text').strip()) # 搜索結(jié)果的標題 title = result.get_attribute('text').strip() # 搜索結(jié)果的網(wǎng)址 link = result.get_attribute('href') # 寫入文件 file.write(f'Title: {title}, link is: {link} n') def tear_down(self):self.browser.close()if __name__ == '__main__': search = Search_Baidu() search.search('selenium') search.tear_down()

到此這篇關于Python使用Selenium自動進行百度搜索的實現(xiàn)的文章就介紹到這了,更多相關Python Selenium自動百度搜索內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持好吧啦網(wǎng)!

相關文章:
主站蜘蛛池模板: 龙江县| 屯门区| 上饶县| 江阴市| 新安县| 进贤县| 肥东县| 衢州市| 南开区| 洮南市| 鄯善县| 岳阳县| 大石桥市| 新田县| 大余县| 梁河县| 巴彦县| 满城县| 封丘县| 军事| 南平市| 靖西县| 米林县| 泰来县| 樟树市| 天台县| 蓝山县| 惠州市| 甘德县| 吉木萨尔县| 云浮市| 英山县| 旌德县| 太和县| 青田县| 晋城| 佛坪县| 民丰县| 古蔺县| 台山市| 荆州市|