简体   繁体   English

使用 selenium webdriver 无法定位动态元素

[英]Trouble locating dynamic element using selenium webdriver

I am working on locating the first name box on facebook.com after you click on create an account.单击创建帐户后,我正在查找 facebook.com 上的名字框。 The id changes with every refresh so I am having a hard time locating it. id 每次刷新都会改变,所以我很难找到它。 The id is always u_somenumber_b. id 始终是 u_somenumber_b。 Such as id = u_1_b, u_2_b etc. Here is what I have so far:例如 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)

When I run code it still doesn't recognize my first_name_element.当我运行代码时,它仍然无法识别我的 first_name_element。 How would I code this to locate this element?我将如何编码来定位这个元素?

It is always a good idea to use simple locators that uniquely describe the element.使用唯一描述元素的简单定位器总是一个好主意。 If the id attribute changes I suggest using the name attribute instead which is static:如果 id 属性发生变化,我建议使用 name 属性,而不是 static:

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

I'm not sure why your xpath failed since you didn't provide the error you get.我不确定为什么您的 xpath 失败,因为您没有提供您得到的错误。

Try with "starts with" and "ends with" CSS selector:尝试使用“开始于”和“结束于”CSS 选择器:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM