【问题标题】:Selenium - find article by h1 and p textSelenium - 查找 h1 和 p 文本的文章
【发布时间】:2021-03-12 04:32:04
【问题描述】:

如何通过如下图的h1和p文字在网站上找到文章?

我试过这个,我可以在其中找到所有文章,但我不知道如何找到带有 h1 中的文本和 p 中的文本的这篇文章。然后我想点击这个。

text = driver.find_elements_by_xpath("//article/div[contains(@class,'inner-article')]/h1")

【问题讨论】:

  • 那你想做什么?如果你想从中提取东西,你可能需要一些抓取库,如果你想点击,请指定什么
  • @Timeler 我想点击这个。
  • 你能告诉我们具体的网址吗?
  • 是的,请提供网址,您想先点击定制豆豆还是红色?
  • @Timeler 我在 html 编辑器 www.w3schools.com 上试过这个。

标签: python selenium xpath css-selectors webdriverwait


【解决方案1】:
text = driver.find_elements_by_xpath("//article/div[contains(@class,'inner-article')][h1/a[contains(text(),"Beanie")]][p/a[contains(text(),"Red")]]")

你可以使用上面的 xpath,它会检查父元素 article/div 是否有子元素 h1/a 和 p/a 分别带有文本 Beanie 和 Red

在 w3chool 中,html 编辑器位于 iframe 中,因此请在您的 seelnium 测试中切换到 iframe,然后再尝试查找元素

【讨论】:

    【解决方案2】:

    要提取和打印文本 Beanie Custom First 和 Red,您需要将 WebDriverWait 诱导为 visibility_of_element_located(),您可以使用以下任一 @987654322 @:

    • 使用CSS_SELECTOR和text属性:

      • 打印Beanie Custom First:

        print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "article.inner-article h1 > a.name-link[href='/shop/asd']"))).text)
        
      • 打印红色:

        print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "article.inner-article p > a.name-link[href='/shop/asd']"))).text)
        
    • 使用XPATH 和get_attribute():

      • 打印Beanie Custom First:

        print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//article[@class='inner-article']//h1/a[@class='name-link' and @href='/shop/asd']"))).get_attribute("innerHTML"))
        
      • 打印红色:

        print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//article[@class='inner-article']//p/a[@class='name-link' and @href='/shop/asd']"))).get_attribute("innerHTML"))
        
    • 注意:您必须添加以下导入:

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

    您可以在How to retrieve the text of a WebElement using Selenium - Python找到相关讨论


    结尾

    链接到有用的文档:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-09-11
      • 2012-08-14
      • 2022-07-13
      • 2022-07-11
      • 1970-01-01
      • 2010-09-21
      • 1970-01-01
      相关资源
      最近更新 更多