I have been learning python and working with selenium for a month or so and I am stuck on one last thing I need for my script.
The script selects an element and clicks on it. I can do this directly but I have realised that the identifier for the element keeps changing so I would like to select it by text.
This is the html snippet:
<a href="javascript:void(0)" style="text-decoration:none;" onclick="getClassDetails('265090', '614617')" class="spinstudio"> <div>
<div class="triangle"></div>
<p style="padding:10px 25px 0 25px;font-size:13px">RPM 80</p>
<p style="font-size:12px;text-align:left;float:left;padding:0;margin:0;">
600 cals
</p>
<p style="font-size:12px;text-align:right;float:right;padding:0;margin:0;">
30 mins
</p>
</div>
</a>
The clickable element is the onclick of course. I have managed to get this working by using the number:
button = driver.find_element_by_xpath("//a[contains(@onclick,'\"getClassDetails('265090')\"')]")
and by xpath:
button = driver.find_element_by_xpath('/html/body/div[12]/div[3]/div[8]/a').click()
but as I said both of those keep changing and I need to run this periodically. So I thought try to select by tag name and then move to the clickable link and click it. And this is where I would like some help please. I have started with this
button = driver.find_element_by_tag_name("//p[contains('RPM 80')]")
and tried some ActionChains options but I am a bit lost.
Also, I think I might have a scenario where there are two elements with the same tag ("RPM 80" for example) on the page. Is there a way to select one of them (I need both selected but separately in different scripts).
Thank you in advance.
For Selection, you can use -
driver.find_element(By.XPATH, '//p[contains(text(),"30 mins")]/preceding-sibling::p[contains(text(),"600 cals")]/parent::div/parent::a[@onclick]')
Don't forget these imports -
from selenium import webdriver
from selenium.webdriver.common.by import By
For Selecting one of the element with 'RPM 80' text -
# This will select the first `p` element with "RPM 80" text
button = driver.find_element_by_xpath("(//p[contains('RPM 80')])[1]")
Let me know if it works.
点击 a 标签试试这个 XPath: driver.find_element(By.XPATH, '//p[text() = "RPM 80"]/parent::div/parent::a').click()
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.