How lookup anchor tag by attribute name and/or

2020-05-08 01:38发布

问题:

This is the web that I am trying to automate:

https://www.supremenewyork.com/shop/sweatshirts/xi9sboa21/u2te1fdw8

My requirement is to click on the image depending on the color entered as input. For example, if "red" is entered as input I must click in the red sweatshirt like the previous picture.

Target images are in <li><a>:

<ul class="styles">
   <li><a class="" data-images="..." data-style-name="Red" data-style-id="22898" href="...">
     <img src="//assets.supremenewyork.com/168724/sw/RymAY-fhCvA.jpg" alt="Rymay fhcva" width="32" height="32"></a>
   </li>
   <li><a class="" data-images="..." data-style-name="Natural" data-style-id="22899" href="...">
     <img src="//assets.supremenewyork.com/168722/sw/P9adXZbmQQ4.jpg" alt="P9adxzbmqq4" width="32" height="32"></a>
   </li>
   <li><a class="" data-images="..." data-style-name="Navy" data-style-id="22900" href="...">
     <img src="//assets.supremenewyork.com/168723/sw/nC1YwBFpU5g.jpg" alt="Nc1ywbfpu5g" width="32" height="32"></a>
   </li>
   <li><a class="" data-images="..." data-style-name="Black" data-style-id="22901" href="...">
     <img src="//assets.supremenewyork.com/168721/sw/viAmPE40S9U.jpg" alt="Viampe40s9u" width="32" height="32"></a>
   </li>
</ul>

In the data-style-name="Red" attribute.

I tried with this:

driver.find_element_by_xpath('//a[@itemprop="model">{}</p>]'.format(color.get()))

But it does not seem to find it.

How can I achieve this?

Thanks

回答1:

Here some approaches:

  • You can lookup the <a> who has data-style-name=YourColor using xpath:

driver.find_element_by_xpath('//a[@data-style-name="Red"]')
  • Loop through the all <a> and compare the data-style-name attribute value with the input color:

elems = driver.find_elements_by_xpath("//a[@href]")
for elem in elems:
    print elem.get_attribute("data-style-name")


回答2:

Use following XPath :

XPATH : //p[@class='style protect' and normalize-space()='"+COLOR_VALUE_VARIABLE+"']

driver.find_element_by_xpath("//p[@class='style protect' and normalize-space()='"+COLOR_VALUE_VARIABLE+"']")