如何使用 Python 點選 Bootstrap 標籤中的 a href 連結?
Bootstrap 是一個流行的 HTML、CSS、JavaScript 框架,它可以幫助我們開發響應式、移動優先的前端 Web 應用程式。它提供了表單、排版、導航、按鈕和其他介面元件的設計模板。Python 是操作 Web 內容的最佳語言。
Selenium 庫
如果我們需要使用 Python 程式設計點選連結,則應該使用 Selenium 庫。它是最流行的開源自動化測試工具,允許我們使 Web 瀏覽器自動化。
Selenium 主要用於自動化 Web 應用程式的測試目的,也用於其他目的,如自動化重複性任務和 Web 抓取。它支援 Python、Java、C 和 Ruby 等程式語言。它可以用來測試 Google、Mozilla Firefox、Safari 等 Web 瀏覽器。
需要遵循的步驟
以下是使用 Selenium 自動開啟 Bootstrap 標籤中給定 href 連結的步驟。
安裝 Selenium 庫:首先,我們必須在 Python 環境中安裝 Selenium 庫。以下是程式碼
pip install Selenium
如果安裝成功,我們將得到以下輸出 -
Collecting Selenium Downloading selenium-4.8.3-py3-none-any.whl (6.5 MB) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Installing collected packages: outcome, h11, exceptiongroup, async-generator, wsproto, trio, trio-websocket, Selenium Successfully installed Selenium-4.8.3 async-generator-1.10 exceptiongroup-1.1.1 h11-0.14.0 outcome-1.2.0 trio-0.22.0 trio-websocket-0.10.2 wsproto-1.2.0 Note: you may need to restart the kernel to use updated packages.
匯入 Web 驅動程式 - Selenium 包用於從 Python 自動化 Web 瀏覽器互動。支援多種瀏覽器/驅動程式(Firefox、Chrome、Internet Explorer),以及遠端協議。
從 Selenium 庫匯入 webdriver 包。
from selenium import webdriver
在此步驟中,我們將網站的驅動程式與 webdriver 包連結。
web_driver = webdriver.Chrome("D://Myspace/chromedriver.exe")
接下來,我們將使用 webdriver 包的 get() 函式透過分配網站連結來開啟 href 連結。
web_driver.get("https://tutorialspoint.tw/")
讓我們將上面提到的所有步驟組合在一起,並檢視輸出。
from selenium import webdriver web_driver = webdriver.Chrome("D://Myspace/chromedriver.exe") web_driver.get("https://tutorialspoint.tw/") print("The website link opened")
輸出
以下是上述程式碼的輸出,當我們執行程式時,將開啟指定的連結。

示例
以下是另一個使用 Python 從 Bootstrap 標籤中點選 href 連結的示例。
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC url = "https://tutorialspoint.tw" driver_path = "path/to/webdriver" driver = webdriver.Chrome(driver_path) driver.get(url) tab_link = WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.CSS_SELECTOR, 'a[data-toggle="tab"][href="#tab-1"]')) ) tab_link.click() WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.ID, "tab-1")) ) link_url = driver.current_url driver.get(link_url) print(driver.page_source) driver.quit()
輸出
上述程式碼的輸出如下。
