简体   繁体   中英

Selenium Dynamic Element Python

Hello I am using selenium. I have to send key to this input.

<input id="209f0c3d-3222-4caa-b55d-1d4463322fd4" type="email" placeholder="E-posta adresi" value="" name="emailAddress" data-componentname="emailAddress" autocomplete="email" autocorrect="off" autocapitalize="off" spellcheck="false">

<input id="8ccf12d3-e264-43b8-8bbe-70e1f3eef202" type="email" placeholder="E-posta adresi" value="" name="emailAddress" data-componentname="emailAddress" autocomplete="email" autocorrect="off" autocapitalize="off" spellcheck="false">

For example every refresh, input id is changing. How can I find this element with selenium

you can find them by xpath

ie:

<html>
 <body>
  <form id="loginForm">
</body>
<html>

you can get by:

login_form = driver.find_element_by_xpath("/html/body/form[1]")

the number 1 here indicates that its the first form. in your case if you know the form you can use the following(just change the number to match yours. ie if its the 4th input then change the value to 4)

driver.find_element_by_xpath("//form[1]/input[1]")

also another alternative is in cases where name, type and some other attributes don't change you can use(chaining them so they point to a unique element):

driver.find_element_by_xpath("//input[@name='emailAddress'][@type='email']")

to validate if the xpath will work, try the search box in the web inspector, it accept xpath and if it finds your element, then it will work in python too.

refer to https://selenium-python.readthedocs.io/locating-elements.html for more ways.

You Can Locate element using xpath kr css where id or classname is not unique.

driver.find_element_by_xpath("//input[@name='emailAddress']")

Or

driver.find_element_by_name('emailAddress')

Or

driver.find_element_by_css_selector("input[name='emailAddress']")

Note: you can do chaining aswell if combination of attributes are unique:

driver.find_element_by_xpath("//input[@name='emailAddress'][@type='email']")

You use any of the unique selectors for the input field: type="email" placeholder="E-posta adresi" value="" name="emailAddress" data-componentname="emailAddress"

xpath:

driver.find_element_by_xpath("//input[@name='emailAddress' and contains(@placeholder, 'E-posta adresi']")

css:

driver.find_element_by_css_selector("input[name='emailAddress'][type='email']")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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