WebDriver无法识别元素

时间:2015-12-08 17:51:39

标签: python firefox selenium selenium-webdriver wait

我正在尝试让Selenium等待特定元素(靠近页面底部),因为我必须等到页面完全加载。

我对它的行为感到困惑。

我不是Selenium的专家,但我期待这项工作:

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

driver = webdriver.Firefox()
wait = WebDriverWait(driver, 10)

    def load_page():
        driver.get('http://www.firmy.cz/?geo=0&q=hodinov%C3%BD+man%C5%BEel&thru=sug')
        wait.until(EC.visibility_of_element_located((By.PARTIAL_LINK_TEXT, 'Zobrazujeme')))
        html = driver.page_source
        print html

    load_page()

TIMEOUT:

File "C:\Python27\lib\site-packages\selenium\webdriver\support\wait.py", line 78, in until
raise TimeoutException(message, screen, stacktrace)
selenium.common.exceptions.TimeoutException: Message: 

我只是想看到满载页面的HTML。它引发TimeoutException,但我确信那个元素已经存在。我已经尝试过另一种方法。

wait.until(EC.visibility_of_element_located(driver.find_element_by_xpath('//a[@class="companyTitle"]')))

但这种做法也引发了错误:

selenium.common.exceptions.NoSuchElementException:
Message: Unable to locate element:
{"method":"xpath","selector":"//a[@class=\"companyTitle\"]"}

2 个答案:

答案 0 :(得分:0)

加载网站需要很长时间,请使用implicitly waiting

在这种情况下,当您对整个HTML感兴趣时,您不必等待页面底部的特定元素。
如果您通过load_page为浏览器提供足够的时间来执行此操作,HTML函数将在加载整个网站后立即打印implicitly_wait()

from selenium import webdriver


driver = webdriver.Firefox()
# wait max 30 seconds till any element is located
# or the site is loaded
driver.implicitly_wait(30)


def load_page():
    driver.get('http://www.firmy.cz/?geo=0&q=hodinov%C3%BD+man%C5%BEel&thru=sug')
    html = driver.page_source
    print html

load_page()

答案 1 :(得分:0)

代码中的主要问题是错误的选择器。

如果您想等到装载了文本Zobrazujeme的网络元素,然后打印页面来源:

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

driver = webdriver.Firefox()
wait = WebDriverWait(driver, 10)

def load_page():
    driver.get('http://www.firmy.cz/?geo=0&q=hodinov%C3%BD+man%C5%BEel&thru=sug')
    wait.until(EC.visibility_of_element_located((By.CLASS_NAME , 'switchInfoExt')))
    html = driver.page_source
    print html

load_page()