【问题标题】:Trying to autofill a data form with selenium and python尝试使用 selenium 和 python 自动填充数据表单
【发布时间】:2020-02-14 03:17:18
【问题描述】:

我正在尝试使用 python 和 selenium 构建一个自动化脚本。这是到目前为止的代码。出于隐私原因,我将敏感信息设为空白。我基本上希望处理单元框自动填充处理单元变量。

from selenium import webdriver
from selenium.webdriver.common.by import By

OriginZip = 99501
DestinationZip = 94016
HandlingUnit = 1

driver = webdriver.Chrome(r"C:\Users\*******\Desktop\WebAutomation\chromedriver")
driver.maximize_window()


driver.get("***********")
driver.implicitly_wait(1)

#Login Page
driver.find_element(By.XPATH, "//button[@id='dropdownMenuButton']").click()
driver.find_element(By.XPATH, "//input[@id='UserName']").send_keys('*******')
driver.find_element(By.XPATH, "//input[@id='Password']").send_keys('*******')
driver.find_element(By.XPATH, "//button[@class='btn btn-primary btn-block']").click()

#2nd Page
driver.find_element(By.XPATH, "//input[@id='OriginZip']").send_keys(OriginZip)
driver.find_element(By.XPATH, "//input[@id='DestinationZip']").send_keys(DestinationZip)
driver.find_element(By.XPATH, "//button[@class='btn btn-secondary form-control']").click()

#3rd Page
driver.refresh()  #<-- Add this to fix
driver.find_element(By.XPATH, "//input[@id='handlingunits']").send_keys(HandlingUnit) #here is where the error occurs

这是第三页的图片

出现的错误:

StaleElementReferenceException: Message: stale element reference: element is not attached to the page document
  (Session info: chrome=80.0.3987.87)

我尝试添加一个implicity_wait 方法,以及按ID 查找元素。有人知道这个问题的正确解决方案吗?

【问题讨论】:

标签: python-3.x selenium selenium-webdriver xpath


【解决方案1】:

你可以试试这个-

1 .在输入数据之前刷新页面。

2.尽量用CSS代替xpath

3.使用try and catch

例如

try:
driver.find_element_by_css_selector("#handlingunits']").send_keys(HandlingUnit) 

except (StaleElementReferenceException):

     wait=WebDriverWait(driver, 5,ignored_exceptions=ignored_exceptions).until(..your code))
     driver.find_element_by_css_selector("#handlingunits").send_keys(HandlingUnit)

希望对你有帮助

【讨论】:

  • Python 对缩进敏感。请修正您的代码缩进。
  • 添加:driver.refresh() 修复它。
【解决方案2】:

以下代码行似乎正在发生 AJAX 刷新

driver.find_element(By.XPATH, "//button[@class='btn btn-secondary form-control']").click()

即使不是最佳实践,我还是建议在这行代码之后显式等待,这也是相当长的时间(例如 30 秒)。 如果有帮助,您可以尝试:

  1. 通过逐步减少显式等待时间来优化显式等待时间
  2. 尝试其他脚本同步技术,例如WebDriverWait

【讨论】:

    猜你喜欢
    • 2021-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-11
    相关资源
    最近更新 更多