Reputation: 1
My aim is to find an element by text (in this case a button), then navigate to the div that contains this button, then find and click another element within that div (The listing title).
My expected results were that the program would locate an element within the page with the text "Add to cart" (if there is one), navigate to the parent div, then search that div for a class called "title" and click it. The actual behavior is slightly different. The program will locate a button, navigate to its parent but then it appears to just search the whole page for the title element and select the first one.
My question is: How do I search only the div I have stored as a variable for a specific class.
inStockButton = driver.find_element_by_xpath('//button[text()="Add to Basket"]')
inStockButtonParent = inStockButton.find_element_by_xpath('//span/ancestor::div[1]')
productToClick = inStockButtonParent.find_element_by_xpath('//*/div[1]/h3/a')
productToClick.click();
Upvotes: 0
Views: 584
Reputation: 101
Try this if your element is within 50 pixels of your orgin element.
inStockButton = driver.find_element_by_xpath('//button[text()="Add to Basket"]') driver.find_element_by_xpath('//h3/a').near(inStockButton).click()
Upvotes: 0
Reputation: 2461
use relative xpaths:
inStockButton = driver.find_element_by_xpath('//button[text()="Add to Basket"]')
inStockButtonParent = inStockButton.find_element_by_xpath('.//span/ancestor::div[1]')
productToClick = inStockButtonParent.find_element_by_xpath('.//*/div[1]/h3/a')
productToClick.click();
Upvotes: 0