测试网站:Web form
相对定位的方法:
- above():定位基准元素上方的元素
- below():定位基准元素下方的元素
- to_left_of():定位基准元素左侧的元素
- to_right_of():定位基准元素右侧的元素
- near() :定位基准元素附近50个像素以内的元素
其中上下还能和左右组合进行链式相对定位,如locate_with().below().to_right_of()
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.relative_locator import locate_with
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/web-form.html")
# 基准元素
refer_element = driver.find_element(By.NAME, "my-password")
# 定位到Text input输入框,并输入Selenium
element_above = driver.find_element(locate_with(By.ID, "my-text-id").above(refer_element))
element_above.send_keys("Selenium")
time.sleep(5)
# 定位到Disabled input框,并获取文本内容
element_below = driver.find_element(locate_with(By.NAME, "my-disabled").below(refer_element))
print(element_below.get_attribute("placeholder"))
# 定位到Default checkbox,并勾选
element_checkbox = driver.find_element(locate_with(By.ID, "my-check-2").below(refer_element))
if not element_checkbox.is_selected():
element_checkbox.click() # 选中复选框
else:
element_checkbox.click() # 取消选中
element_near = driver.find_element(locate_with(By.CSS_SELECTOR, "textarea[name='my-textarea']").near(refer_element))
print(element_near.get_attribute("rows"))
time.sleep(5)
driver.quit()
# element_left = driver.find_element(locate_with(By.ID, "my-text-id").to_right_of(refer_element))