【问题标题】:Selenium Python - Test if an element exists in the pageSelenium Python - 测试页面中是否存在元素
【发布时间】:2014-07-25 07:56:59
【问题描述】:

我是 Selenium 的新手,我想编写一个 Python 脚本,在 google 上搜索一些关键字并在找到关键字时自动打开一个页面。

我一直在尝试使用来自 website 的脚本:

from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import NoSuchElementException

if __name__ == "__main__":
    driver = webdriver.Firefox()
    wait = WebDriverWait(driver, 100)
    driver.get("http://google.com")

    inputElement = driver.find_element_by_name("q")
    inputElement.send_keys("Irwin Kwan")

    wait.until(EC.element_to_be_clickable((By.XPATH,"//a[@href='http://irwinhkwan.wordpress.com/']")))
    blog = driver.find_element_by_xpath("//a[@href='http://irwinhkwan.wordpress.com/']")
    blog.click()

    driver.quit()

如果 xpath 显示在页面中,它可以完美地工作。但是,如果不是,我们将永远等待。

如何检查一个元素是否存在,如果存在我点击它?

我尝试使用文档中给出的“try”或NoSuchElementException,但我承认与“双重否定;-)混淆了:

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

driver = webdriver.Firefox()
driver.get("http://somedomain/url_that_delays_loading")
try:
    element = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.ID, "myDynamicElement"))
    )
finally:
    driver.quit()

最终,我想要一个 while 循环,它会转到谷歌结果的第 X 页,并在每次找到特定地址时单击。

如果有人能帮我一把,那就太好了!我很确定这是微不足道的,但是尽管在线提供了所有文档,但在过去的几天里我一直无法解决这个问题......

【问题讨论】:

  • 在您的第二个块中,您并没有真正完成尝试/异常。如果您在finally: 行之前包含except NoSuchElementException: print "Element was not found",您的程序将打开页面,等待10 秒以使元素出现,允许您与之交互,否则在10 秒内找不到它,将打印出消息。无论哪种方式,它都会在最后关闭浏览器。
  • 感谢您的回答。 NoSuchElementException' 和 'else if' 是一样的吗?如果我放除了 NoSuchElementException: print "Element was not found",即使链接在页面上,它也会始终打印。我想要什么:1)尝试找到最大的链接。 10s 2)如果找到,则点击它或3)如果找不到,driver.quit()。
  • 可以考虑使用这样的异常捕获,如果/否则我猜。 Try this, if it works do this, else do something else other than blowing up.如果您总是看到打印行,可能是您的选择器不正确?
  • @MarkRowlands 我已经写了一个答案来向你展示我尝试过的代码

标签: python selenium xpath


【解决方案1】:

这是我为 WebElement 编写的一个小包装,希望对您有所帮助

class Element(object):

    def __init__(self, xpath=None):
        self.xpath = xpath

    def __get_element(self):
        return Driver().find_element_by_xpath(self.xpath)


    def is_exist(self):
        try:
           return self.__get_element().is_displayed()
        except NoSuchElementException, e:
            logger.exception(e.message)
            return False

你不能点击一个不可见的元素,首先你需要暴露它,然后才点击。

希望对你有帮助

【讨论】:

  • 谢谢!我现在要试试 :-)
猜你喜欢
  • 2011-12-20
  • 1970-01-01
  • 2013-11-11
  • 1970-01-01
  • 2018-01-23
  • 2021-05-17
  • 2014-06-23
  • 1970-01-01
  • 2020-01-31
相关资源
最近更新 更多