【问题标题】:Selenium, webdriver - after can't find xpath Should the browser close. pythonSelenium,webdriver - 之后找不到 xpath 浏览器是否应该关闭。 Python
【发布时间】:2020-08-28 19:14:56
【问题描述】:

您好,我是新来的,我有一个问题。它是关于我网站的帐户创建者的。 ..

email = driver.find_element_by_xpath('//*[@id="elInput_email"]')
email.send_keys(email_str)

有时会显示错误:消息:无法找到元素://*[@id="elInput_email"]

关闭浏览器而不检查我该怎么做最好?

我试试

if not driver.find_element_by_xpath('//*[@id="elInput_email"]'):driver.close() 
else: email.send_keys(email_str)

但不起作用。

如果找不到 XPATH,我希望关闭 webdrive(浏览器)。

【问题讨论】:

  • 为什么你不能把你的测试包装在异常处理中并作为 finally 的一部分关闭浏览器。
  • 如果找不到 xpath,我如何关闭 driverweb?我没有那么多经验:)
  • 提供下面的伪代码,导航或加载页面时,您几乎可以对所有元素使用wait.until(EC.presence_of_element_located((By.XPATH,'xpath_goes_here')))。这样脚本将在进入 finally 块之前等待指定时间的最大值。
  • 我没有看到带有finally 实现的代码。
  • 是的,因为它不起作用!

标签: python selenium selenium-webdriver xpath helper


【解决方案1】:

这是伪代码。

显式等待所需的导入

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

脚本应该是

# initiate your driver instance

# navigate to the page

try:
    # wait for the element using explicit wait(waiting for max of 10 seconds)
    wait = WebDriverWait(driver, 10)
    email = wait.until(EC.presence_of_element_located((By.XPATH,'//*[@id="elInput_email"]')))
    email.send_keys(email_str)
finally:
    # close the browser here
    driver.quit()

【讨论】:

  • 如果您认为问题已解决,请点击我的回答左侧的复选标记接受回答。为了未来的访问者的利益,请随时为答案投票。
  • 感谢您的回答,我遇到了错误。文件“C:\test.py”,第 24 行 wait = DriverWait(driver, 10) ^ IndentationError: unexpected indent
  • 应该是WebDriverWait 而不是DriverWait
  • 刚刚测试过。错误消息还带有 wait = WebDriverWait (driver, 10)
  • 确保您有正确的缩进。错误说,该行的缩进不正确。如果您仍然面临问题,请使用当前代码更新问题。以便我们检查代码有什么问题。
猜你喜欢
  • 1970-01-01
  • 2012-07-25
  • 2016-10-31
  • 1970-01-01
  • 2014-01-27
  • 2013-02-17
  • 1970-01-01
  • 2022-12-05
  • 2018-03-09
相关资源
最近更新 更多