簡體   English   中英

使用 selenium webdriver 無法定位動態元素

[英]Trouble locating dynamic element using selenium webdriver

單擊創建帳戶后,我正在查找 facebook.com 上的名字框。 id 每次刷新都會改變,所以我很難找到它。 id 始終是 u_somenumber_b。 例如 id = u_1_b, u_2_b 等。這是我目前所擁有的:

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

# Open the Firefox browser
driver = webdriver.Chrome()

# Navigate to “http://qatechhub.com
driver.get('http://www.fb.com')

# Check current URL
url = driver.current_url
print(url)
assert url == 'https://www.facebook.com/'
print("URL confirmed")

# Verify that there is a “Create an account” section on the page.
create_account_css_locator = "a[id='u_0_2']"

# create_account_css_locator = "a#u_0_2" Also works here
create_account_element = driver.find_element_by_css_selector(
    create_account_css_locator)
assert create_account_element.text == 'Create New Account'
print("Create an account section confirmed")
create_account_element.click()


# Fill in the text boxes: First Name, Last Name, Mobile Number or email address,
#  “Re-enter mobile number”, new password.
first_name_xpath = "//input[starts-with(@id, 'u_') and contains(@id, '_b')]"
first_name_element = driver.find_element_by_xpath(first_name_xpath)
print(first_name_element)

當我運行代碼時,它仍然無法識別我的 first_name_element。 我將如何編碼來定位這個元素?

使用唯一描述元素的簡單定位器總是一個好主意。 如果 id 屬性發生變化,我建議使用 name 屬性,而不是 static:

first_name_xpath = "//input[@name='firstname']"

我不確定為什么您的 xpath 失敗,因為您沒有提供您得到的錯誤。

嘗試使用“開始於”和“結束於”CSS 選擇器:

a[id^="u_"][id$="_b"]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM