Selenium Error Try/Except,元素未附加到pag

2024-04-18 23:52:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在做一个程序,其中一个用户登录到他的帐户(100%完成),然后它去一个网站(网址:www.site.com(不是这个tho)并搜索元素。问题是:元素并不总是在那里,它随机弹出,所以我想做一个程序,当它没有得到一滴(糖果)它去另一个标签。你知道吗

我试过很多东西,改变循环,从try中添加/删除东西,除了。。。你知道吗

for i in range(10000):
    while True:
        print("Starting!")
        try:
            element = browser.find_element_by_xpath('//*[@id="redeem-candy-voucher"]')#.click()
        except NoSuchElementException:
            pass
        browser.execute_script("arguments[0].click();", element)

        print("Clicked Candy! Skullbux Gained!")

        time.sleep(3)

        browser.execute_script("window.open('');")
        browser.switch_to.window(browser.window_handles[1])
        browser.get("https://www.brickplanet.com/events/trick-or-treat")

        time.sleep(3)

        try:
            element = browser.find_element_by_xpath('//*[@id="redeem-candy-voucher"]')#.click()
        except NoSuchElementException:
            pass
        browser.execute_script("arguments[0].click();", element)

        print("Clicked Candy! 0.25 Gained!")
        #browser.close()
        time.sleep(5)

有两个可能的错误。 在其中找到元素,然后刷新页面,然后出现错误:

DevTools listening on ws://127.0.0.1:52479/devtools/browser/a2cfa4b3-e538-49fb-872c-114db52513ce
Starting!
Clicked Candy! Skullbux Gained!
Traceback (most recent call last):
  File "C:\Users\DOMA\Desktop\bp hack.py", line 54, in <module>
    browser.execute_script("arguments[0].click();", element)
  File "C:\Users\DOMA\AppData\Local\Programs\Python\Python36-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 636, in execute_script
    'args': converted_args})['value']
  File "C:\Users\DOMA\AppData\Local\Programs\Python\Python36-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
    self.error_handler.check_response(response)
  File "C:\Users\DOMA\AppData\Local\Programs\Python\Python36-32\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attached to the page document
  (Session info: chrome=77.0.3865.90)

当它找不到任何元素时:

DevTools listening on ws://127.0.0.1:52432/devtools/browser/9250b0fb-2742-4a8b-9043-b7cdbec1f8e3
Starting!
Traceback (most recent call last):
  File "C:\Users\DOMA\Desktop\bp hack.py", line 38, in <module>
    browser.execute_script("arguments[0].click();", element)
NameError: name 'element' is not defined

Process returned 1 (0x1)        execution time : 20.796 s
Press any key to continue . . .

Tags: inpybrowser元素executelinescriptsite
2条回答

之所以发生StaleElementReferenceException,是因为您正在刷新页面。刷新页面后,所定位的元素就不是同一个元素,因此需要重新找到该元素以获得新实例。你知道吗

我会在元素上添加一个wait,这也可以解决找不到元素的情况:

# Wait for element to exist
element = WebDriverWait(driver, 15).until(EC.presence_of_element_located((By.XPATH, "//*[@id='redeem-candy-voucher']")))

browser.execute_script("arguments[0].click();", element

至于StaleElement问题,如果刷新页面,则需要重新查找元素。举个例子:

# wait and find the element
element = WebDriverWait(driver, 15).until(EC.presence_of_element_located((By.XPATH, "//*[@id='redeem-candy-voucher']")))

# refresh
driver.refresh()

# This will throw an exception!
# element.click()

# Find fresh instance of element to avoid the exception.
element = WebDriverWait(driver, 15).until(EC.presence_of_element_located((By.XPATH, "//*[@id="redeem-candy-voucher"]")))

element.click()

希望这有点帮助。你知道吗

两个问题都有相同的根本原因;当您称之为:

        try:
            element = browser.find_element_by_xpath('//*[@id="redeem-candy-voucher"]')#.click()
        except NoSuchElementException:
            pass
        browser.execute_script("arguments[0].click();", element)

如果element = browser.find_element_by_xpath('//*[@id="redeem-candy-voucher"]')因任何原因失败,则:

  • ^如果代码通过except路由而没有通过try路由,则{}将不被定义。你知道吗
  • 或者element可能引用在第一个try块中找到的元素,但由于该元素未附加到DOM,因此将引发StaleElementReferenceException。你知道吗

你应该做些什么来避免这样的行为:

        try:
            element = browser.find_element_by_xpath('//*[@id="redeem-candy-voucher"]')
            browser.execute_script("arguments[0].click();", element)
        except NoSuchElementException:
            pass

相关问题 更多 >