1. 安裝Selenium庫和浏覽器驅動:在Python環境中使用 pip install selenium 指令安裝Selenium庫,然後下載下傳對應的浏覽器驅動(如Chrome或Firefox的驅動),并儲存到本地磁盤中。
2. 建立WebDriver:使用Selenium庫中的webdriver子產品建立對應的WebDriver對象(如ChromeDriver或FirefoxDriver)。
3. 打開網頁:使用WebDriver對象的get()方法打開網頁。
4. 定位元素:根據元素的屬性(如ID、name、class等)或XPath表達式,使用WebDriver對象的find_element_by_*()方法定位元素。
5. 操作元素:使用定位到的元素對象調用對應的方法進行操作,如輸入文字、點選按鈕、擷取文本等。
6. 關閉WebDriver:使用WebDriver對象的quit()方法關閉浏覽器。
下面是一個簡單的示例代碼,示範了如何使用Selenium庫和Chrome浏覽器驅動打開百度網頁并搜尋“Python”:
``` python
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
# 建立Chrome浏覽器驅動
driver = webdriver.Chrome()
# 打開百度網頁
driver.get("網頁連結")
# 找到搜尋框并輸入關鍵字
elem = driver.find_element_by_name("wd")
elem.send_keys("Python")
elem.send_keys(Keys.RETURN)
# 擷取搜尋結果并列印
results = driver.find_elements_by_xpath("//div[@class='result c-container ']")
for result in results:
title = result.find_element_by_tag_name("h3").text
link = result.find_element_by_tag_name("a").get_attribute("href")
print(title)
print(link)
# 關閉浏覽器
driver.quit()
```
這個例子首先建立了一個Chrome浏覽器驅動,然後使用get()方法打開百度網頁,在搜尋框中輸入關鍵字“Python”,并按Enter鍵進行搜尋。接着使用XPath表達式找到所有搜尋結果的元素,并分别擷取它們的标題和連結位址并列印。最後使用quit()方法關閉浏覽器。