Bot硒,Python。 time.sleep(n)错误

时间:2018-10-07 09:56:12

标签: python selenium

如果我需要解析并单击​​DOM元素,还有什么比硒更好的东西吗?

打开的浏览器是可选的(而不是必需的)。

有没有更好的选择呢?

顺便说一句

为什么在此time.sleep(n)之后出现错误。

错误:

Traceback (most recent call last):
  File "main.py", line 39, in <module>
    print("Buy: " + str(elemGreen.text))
  File "C:\Users\Andrew\AppData\Local\Programs\Python\Python37-32\lib\site-packages\selenium\webdriver\remote\webelement.py", line 76, in text
    return self._execute(Command.GET_ELEMENT_TEXT)['value']
  File "C:\Users\Andrew\AppData\Local\Programs\Python\Python37-32\lib\site-packages\selenium\webdriver\remote\webelement.py", line 633, in _execute
    return self._parent.execute(command, params)
  File "C:\Users\Andrew\AppData\Local\Programs\Python\Python37-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
    self.error_handler.check_response(response)
  File "C:\Users\Andrew\AppData\Local\Programs\Python\Python37-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=69.0.3497.100)

我的Python代码:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time

def loginCheck():
    l = driver.find_elements_by_css_selector(".not-login")[0]
    if(l.text == "Login or Join Trading"):
        return True
    else:
        return False

driver = webdriver.Chrome(r"C:\Users\Andrew\Desktop\chromedriver.exe")
driver.get("https://abcc.com/markets/ethusdt")

if(loginCheck() == False):
     print("Next step")
else:
    print("Waiting for the login")
    time.sleep(10)    

1 个答案:

答案 0 :(得分:0)

expected_conditions.visibility_of_all_elements_located的句柄StaleElementReferenceException。您可以使用它来定位元素

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

def loginCheck():
    elements = WebDriverWait(driver, 30).until(expected_conditions.visibility_of_all_elements_located((By.CLASS_NAME, 'not-login')))
    l = elements[0]
    if (l.text == "Login or Join Trading"):
        return True
    else:
        return False