Issue
Still been having trouble creating a function in python using selenium to click a button on a webpage.
Simply I want to be able to press a button on this page (I assume the xpath is the line in the bottom right)
The solution needs to be able to interact with different sizes and I am not skilled enough in creating the xpath and I have found resources for selenium 4 online to be limited.
I've tried:
driver.find_element(By.XPATH, '//label[@value="US7.5W / US6Y"]').click()
and
driver.find_element(By.XPATH, '//label[@value="US7.5W / US6Y"]/html/body/div[2]/div[3]/div[1]/div/section/div/div[2]/div/div/div[1]/div/div/div[2]/form/div[1]/div[4]/div/div[2]/label').click()
Could anyone please help make one that doesnt give me the "no such element: Unable to locate element" error.
I am using selenium in python 3.9 running on spyder.
Solution
Your xpaths are too long. You should try to make it more relative (although that couldn't be the issue necessarily that you got, but it's a good practice to have the xpaths as relative as possible to make them robust). One thing could be that a modal window is occasionally displayed onto the page, disabling all the page actions, as the modal gets active. So, I used a try-except block, just in case if the modal appears, the code closes it. Then, I used class in xpath with index, and the 2nd index is the one that you are looking for, perhaps, so I clicked it. If you are looking for other size button, try checking the index of it and replace with the same. This worked for me.
driver.get('https://www.untiedau.com/products/nike-dunk-low-triple-pink-womens-gs')
time.sleep(5)
try:
driver.find_element(By.XPATH, "(//*[contains(@class, 'needsclick')]//div[@role='dialog']//button)[1]").click()
except:
print('modal not shown')
time.sleep(1)
sz = driver.find_element(By.XPATH, "(//div[@class='product-single__swatch__item'])[2]")
print(sz.text)
sz.click()
Here is the output:
modal not shown
US6.5W / US5Y
Process finished with exit code 0
P.S. You may replace time.sleep
with explicit waits
such as webdriverwait
Answered By - Anand Gautam
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.