溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Python中如何使用Selenium自動進行百度搜索

發(fā)布時間:2022-03-29 16:43:38 來源:億速云 閱讀:244 作者:iii 欄目:移動開發(fā)

這篇文章主要介紹了Python中如何使用Selenium自動進行百度搜索的相關知識,內(nèi)容詳細易懂,操作簡單快捷,具有一定借鑒價值,相信大家閱讀完這篇Python中如何使用Selenium自動進行百度搜索文章都會有所收獲,下面我們一起來看看吧。

安裝 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 webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from 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的webdriver
        url = "https://www.baidu.com/" #這里定義訪問的網(wǎng)絡地址
        self.url = url

        options = 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} 
")

點位網(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自動進行百度搜索

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

Python中如何使用Selenium自動進行百度搜索

找到輸入框的HTML元素,

Python中如何使用Selenium自動進行百度搜索

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

Python中如何使用Selenium自動進行百度搜索

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

Python中如何使用Selenium自動進行百度搜索

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

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

Python中如何使用Selenium自動進行百度搜索

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

Python中如何使用Selenium自動進行百度搜索

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

Python中如何使用Selenium自動進行百度搜索

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

Python中如何使用Selenium自動進行百度搜索

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

Python中如何使用Selenium自動進行百度搜索

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

Python中如何使用Selenium自動進行百度搜索

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

Python中如何使用Selenium自動進行百度搜索

通過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 time
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys

class Search_Baidu:
    def __init__(self):
        url = "https://www.baidu.com/"
        self.url = url

        options = 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

        self.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} 
")

    def tear_down(self):
        self.browser.close()

if __name__ == "__main__":
    search = Search_Baidu()
    search.search("selenium")
    search.tear_down()

關于“Python中如何使用Selenium自動進行百度搜索”這篇文章的內(nèi)容就介紹到這里,感謝各位的閱讀!相信大家對“Python中如何使用Selenium自動進行百度搜索”知識都有一定的了解,大家如果還想學習更多知識,歡迎關注億速云行業(yè)資訊頻道。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。

AI