Selenium Dynamic Element Python

守給你的承諾、 提交于 2020-06-23 14:08:36

问题


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


回答1:


you can find them by xpath

i.e:

<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. i.e 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.




回答2:


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']")



回答3:


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']")


来源:https://stackoverflow.com/questions/61641202/selenium-dynamic-element-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!