如何使用 Selenium 通过 id 查找元素
有关如何使用 Selenium 通过 id 查找元素的分步指南。
重要提示:我们将在本教程中使用真实示例,因此你需要 硒 图书馆和 浏览器驱动程序 安装。
步骤 1。 写下你的第一个 Selenium 脚本.
注意: 我们将使用 Python
以及 Chrome WebDriver。 你可以添加 Chrome 网络驱动程序 至 这个 途径.
步骤 2。 现在让我们通过以下元素找到它 id 通过检查页面源代码来查找任何图书列表。我们在此示例中使用 books.toscrape.com。
首先,你需要导入 By 选择器模块
from selenium.webdriver.common.by import By
TIPS: 定位元素。
步骤 3。 上一步提供了多种查找元素的选项。您可以使用 的CSS 以及 XPath的 选择器或内置 獲得.ID 函数。选择器如下所示:
element_by_id = driver.find_element(By.ID, "product_description").text
element_by_css = driver.find_element(By.CSS_SELECTOR, "#product_description").text
element_by_xpath = driver.find_element(By.XPATH, "//*[@id='product_description']").text
这是 脚本的输出。它显示您刚刚抓取的元素。
结果:
恭喜,您刚刚使用 Selenium 找到并提取了 id 的内容。以下是完整脚本:
from selenium import webdriver
from selenium.webdriver.common.by import By
driver = webdriver.Chrome()
driver.get("http://books.toscrape.com/catalogue/a-light-in-the-attic_1000/index.html")
element_by_id = driver.find_element(By.ID, "product_description").text
element_by_css = driver.find_element(By.CSS_SELECTOR, "#product_description").text
element_by_xpath = driver.find_element(By.XPATH, "//div[@id='product_description']").text
driver.quit()
print (element_by_id)