温馨提示:本文翻译自stackoverflow.com,查看原文请点击:python - How to find element by 2 text?

python - 如何按2个文本查找元素?

发布于 2020-03-27 12:04:44

例如,我有这样的HTML代码。我想通过“ T恤名称”和“颜色-T恤”找到它。这个怎么做?我想找到这种颜色,因为我还有其他一些名称相同但颜色不同的T恤。

<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>

查看更多

查看更多

提问者
konto211541
被浏览
67
KunduK 2019-07-04 00:56

使用WebDriverWaitvisibility_of_all_elements_located跟随xpath实现它。

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)    

您需要导入以下内容以执行上述代码。

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

使用特定颜色的单击选项进行编辑。

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()

发布
问题

分享
好友

手机
浏览

扫码手机浏览