在使用Selenium和Python单击元素之前,如何等待页面加载?

时间:2018-09-06 20:13:26

标签: python selenium web-scraping

我是python的新手,我正在尝试创建代码,以便在页面加载后立即单击按钮,但在之后加载按钮。我尝试过的每件事都失败了,因为有时页面加载时间太长,并且最终该按钮将不会被单击(或者单击得太早)。有谁知道我只有在加载元素时才能立即单击该元素?我读过的一篇文章说,我目前的工作方式(如下所示)对很多其他人都有效,但对我而言却行不通。

    try:
        element = WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.XPATH, "//*[@id='stylesSection']/div[2]/div[2]/a"))
        )
    finally:
        elem2 = driver.find_element_by_xpath("//*[@id='stylesSection']/div[2]/div[2]/a")
        eleme2.click()

    try:
        element = WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.XPATH, "//*[@id='pageContent']/div[3]/div/div[1]/div[2]/div[2]/a"))
        )
    finally:
        elem3 = driver.find_element_by_xpath("//*[@id='pageContent']/div[3]/div/div[1]/div[2]/div[2]/a")
        elem3.click()

    try:
        element = WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.XPATH, "//*[@id='buyUsedPanel']/div[2]/div/div[3]/a"))
        )
    finally:
        elem4 = driver.find_element_by_xpath("//*[@id='buyUsedPanel']/div[2]/div/div[3]/a")
        elem4.click()

编辑: 我试图将时间延长到100,然后再延长到500,但是无论我做什么,它一直在给我这个错误。知道如何阻止这种情况发生吗?

  

File "tester3.py", line 205, in <module> elem2.click() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/selenium/webdriver/remote/webelement.py", line 80, in click self._execute(Command.CLICK_ELEMENT) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/selenium/webdriver/remote/webelement.py", line 628, in _execute return self._parent.execute(command, params) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/selenium/webdriver/remote/webdriver.py", line 320, in execute self.error_handler.check_response(response) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.WebDriverException: Message: unknown error: Element <a class="big-button-one style-link" href="/kia/optima/2013/lx-hybrid-sedan-4d/options/?vehicleid=385282&amp;intent=buy-used&amp;mileage=70160&amp;pricetype=retail&amp;modalview=false">...</a> is not clickable at point (422, 518). Other element would receive the click: <div id="socialToolbar" class="hideForPrint social-toolbar ">...</div>

其他相关文章都在javascript中,我不知道如何在我的python程序中使用该代码。

0 个答案:

没有答案