Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to find elemenst under a located element?

I have a web page something like:

<div class='product-pod-padding'>
 <a class='header product-pod--ie-fix' href='link1'/>
 <div> SKU#1</div>
</div>
<div class='product-pod-padding'>
 <a class='header product-pod--ie-fix' href='link2'/>
 <div> SKU#2</div>
</div>
<div class='product-pod-padding'>
 <a class='header product-pod--ie-fix' href='link3'/>
 <div> SKU#3</div>
</div>

When I tried to loop through the products with the following code, it will give us expected outcome:

products=driver.find_elements_by_xpath("//div[@class='product-pod-padding']")
for index, product in enumerate(products):    
   print(product.text)


SKU#1
SKU#2
SKU#3

However, if I try to locate the href of each product, it will only return the first item’s link:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

products=driver.find_elements_by_xpath("//div[@class='product-pod-padding']")
for index, product in enumerate(products):
   print(index)   
   print(product.text)
   url=product.find_element_by_xpath("//a[@class='header product-pod--ie-fix']").get_attribute('href')
   print(url)

   SKU#1
   link1
   SKU#2
   link1
   SKU#3
   link1

What should I do to get the corrected links?

>Solution :

This should make your code functional:

[...]
products=driver.find_elements_by_xpath("//div[@class='product-pod-padding']")
for index, product in enumerate(products):
   print(index)   
   print(product.text)
   url=product.find_element_by_xpath(".//a[@class='header product-pod--ie-fix']").get_attribute('href')
   print(url)
[..]

The crux here is the dot in front of xpath, which means searching within the element only.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading