Reputation: 3
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!
Here is my python code:
broswer.find.element_by_xpath('//*[@id="wiki-edit-wikiEdit26"]/div/div/div/div[2]/a[1]') .click()
Upvotes: 0
Views: 1003
Reputation: 736
You can use starts-with
or contains
broswer.find.element_by_xpath("//*[contains(@id,'wiki-edit-wikiEdit')]/div/div/div/div[2]/a[1]").click()
Also, using such long xpath's is not recommended. Use css-selectors
over xpath
.
Upvotes: 0
Reputation: 3409
You can use matches
in xpath to do this,
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]
Upvotes: 1
Reputation: 125
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()
Upvotes: 0