【问题标题】:How to find element by 2 text?如何通过 2 个文本查找元素?
【发布时间】:2019-07-03 15:49:54
【问题描述】:

例如,我有这样的 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>

【问题讨论】:

  • 到目前为止你有什么?你尝试了什么?
  • 你知道beautifulsoup4图书馆吗?
  • @abdusco 我试过 find_element_by_xpath("//a[text()='T-shirt name']") 但它把我扔掉了 "selenium.common.exceptions.NoSuchElementException: Message: Unable to定位元素:"
  • 你的问题不清楚你想通过其他元素的文本来查找一个元素吗?
  • @konto211541 请剪切更多 HTML

标签: python selenium selenium-webdriver


【解决方案1】:

使用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 color : ' + 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 color : ' + 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()

【讨论】:

  • 好的,现在如何点击例如T 恤颜色 == “红色”?
  • 用 If 条件检查第二个打印值并单击。我现在不在,我稍后会回来
  • @konto211541 : 检查编辑部分
【解决方案2】:

您可以使用 BeautifulSoup 进行解析 soup.find_all("a", string="T-shirt name")

similar answer

【讨论】:

    猜你喜欢
    • 2016-08-22
    • 2019-10-07
    • 2012-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-25
    相关资源
    最近更新 更多