Warm tip: This article is reproduced from stackoverflow.com, please click
python selenium

How to find element by 2 text?

发布于 2020-03-27 10:31:37

For exaple, I have HTML code like this. And I want to find this by "T-shirt name" and "Color - T-shirt". How to do this? And I want to find this color because I have a few more T-shirt with the same name but different color.

<article>
  <div class="article">
    <a style="height:150px;" href="/shop/t-shirt">
      <img src="//blablabla.jpg" alt="asdasdas" width="150" height="150">
      <h1><a class="name-link" href="/shop/t-shirt/">T-shirt name</a>
      </h1>
      <p><a class="name-link" href="/shop/t-shirt/">>Color</a></p>
  </div>
</article>
<article>
  <div class="article">
    <a style="height:150px;" href="/shop/t-shirt">
      <img src="//blablabla.jpg" alt="asdasdas" width="150" height="150">
      <h1><a class="name-link" href="/shop/t-shirt/">T-shirt name</a>
      </h1>
      <p><a class="name-link" href="/shop/t-shirt/">>second Color</a></p>
  </div>
</article>
Questioner
konto211541
Viewed
95
KunduK 2019-07-04 00:56

Use WebDriverWait and visibility_of_all_elements_located and following xpath to achieve it.

elements=WebDriverWait(driver,20).until(EC.visibility_of_all_elements_located((By.XPATH,"//h1/a[@class='name-link' and contains(.,'T-shirt name')]")))
for element in elements :

    print('T shirt name : ' +element.text)
    print('T Shirt collor : ' + element.find_element_by_xpath("./following::p/a[@class='name-link']").text)    

You need to import followings to execute above code.

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

EDITED With click option for a particular color.

elements=WebDriverWait(driver,20).until(EC.visibility_of_all_elements_located((By.XPATH,"//h1/a[@class='name-link' and contains(.,'T-shirt name')]")))
for element in elements :

    print('T shirt name : ' +element.text)
    print('T Shirt collor : ' + element.find_element_by_xpath("./following::p/a[@class='name-link']").text)
    if element.find_element_by_xpath("./following::p/a[@class='name-link']").text=='RED':
        element.find_element_by_xpath("./following::p/a[@class='name-link']").click()