How can I find the randomly Xpath using Selenium?


How can I find the randomly Xpath using Selenium?



I am a newer in Selenium and use python to build it. Recently, I found a question which want to ask someone who can help me to figure it. The question is the Xpath I want to get is randomly, for example:



'//*[@id="wiki-edit-wikiEdit26"]/div/div/div/div[2]/a[1]'



'//*[@id="wiki-edit-wikiEdit27"]/div/div/div/div[2]/a[1]'



'//*[@id="wiki-edit-wikiEdit28"]/div/div/div/div[2]/a[1]'



These three xpath are used on the same button, but the number after wikiEdit will be changed every time. Therefore, are there any way which can help me to run my script more smoothly? Thank you very much!


xpath



Here is my python code:


broswer.find.element_by_xpath('//*[@id="wiki-edit-wikiEdit26"]/div/div/div/div[2]/a[1]') .click()





do you want to change no. in wikiEdit ?
– Raghav Patnecha
33 mins ago





Please ass sample block of HTML
– Ishita Shah
31 mins ago





No, I just want to let my script run smoothly, because the xpath I mentioned will be changed when every time I get it. This would make my script be unstable
– Potter Chen
30 mins ago





Either use matches or contains text with the string up to "wikiEdit" or else use other locator because id attribute with alphanumeric values will mostly change its values.
– Gautam Bothra
22 mins ago





3 Answers
3



You just need to format your string..


import random
# Random range 1 - 100
x = random.randint(1,100)

broswer.find.element_by_xpath(f'//*[@id="wiki-edit-wikiEdit{x}"]/div/div/div/div[2]/a[1]') .click()



You can use matches in xpath to do this,


matches


broswer.find.element_by_xpath('//*[matches(@id, '^(wiki-edit-wikiEdit)[0-9]')]/div/div/div/div[2]/a[1]') .click()



so basically that matches the id anything starting wiki-edit-wikiEdit followed by numbers form [0-9]


wiki-edit-wikiEdit


[0-9]





Hi, it seen have some error on this script as below. File "C:Autotttt.py", line 37 jira.find_element_by_xpath('//*[matches(@id, '^(wiki-edit-wikiEdit)[0-9]')]/div/div/div/div[2]/a[1]').click() ^ SyntaxError: invalid syntax
– Potter Chen
17 mins ago




You can use starts-with or contains


starts-with


contains


driver.findElement(By.xpath("//*[contains(@id,'wiki-edit-wikiEdit')]/div/div/div/div[2]/a[1]")



Also, using such long xpath's is not recommended. Use css-selectors over xpath.


css-selectors


xpath






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Comments

Popular posts from this blog

paramiko-expect timeout is happening after executing the command

how to run turtle graphics in Colaboratory

Export result set on Dbeaver to CSV