Python Selenium 中的元素定位技术

2023-04-17 00:00:00 技术 元素 定位

Python Selenium 中的元素定位技术可以通过以下几种方式进行:

  1. By ID:通过元素的 ID 属性进行定位。示例代码:
from selenium import webdriver

driver = webdriver.Chrome()
driver.get("http://pidancode.com")

element = driver.find_element_by_id("header")
  1. By Name:通过元素的 Name 属性进行定位。示例代码:
from selenium import webdriver

driver = webdriver.Chrome()
driver.get("http://pidancode.com")

element = driver.find_element_by_name("s")
  1. By Class Name:通过元素的 Class Name 进行定位。示例代码:
from selenium import webdriver

driver = webdriver.Chrome()
driver.get("http://pidancode.com")

element = driver.find_element_by_class_name("entry-title")
  1. By Tag Name:通过元素的标签名进行定位。示例代码:
from selenium import webdriver

driver = webdriver.Chrome()
driver.get("http://pidancode.com")

element = driver.find_element_by_tag_name("h1")
  1. By Link Text:通过链接文本进行定位。示例代码:
from selenium import webdriver

driver = webdriver.Chrome()
driver.get("http://pidancode.com")

element = driver.find_element_by_link_text("皮蛋编程")
  1. By Partial Link Text:通过链接的部分文本进行定位。示例代码:
from selenium import webdriver

driver = webdriver.Chrome()
driver.get("http://pidancode.com")

element = driver.find_element_by_partial_link_text("编程")
  1. By XPath:通过 XPath 表达式进行定位。示例代码:
from selenium import webdriver

driver = webdriver.Chrome()
driver.get("http://pidancode.com")

element = driver.find_element_by_xpath("//h1[@class='entry-title']")
  1. By CSS Selector:通过 CSS Selector 进行定位。示例代码:
from selenium import webdriver

driver = webdriver.Chrome()
driver.get("http://pidancode.com")

element = driver.find_element_by_css_selector(".entry-header")

相关文章