【问题标题】:Selenium Webdriver Timeout (Python 2.7)Selenium Webdriver 超时(Python 2.7)
【发布时间】:2017-12-25 03:07:55
【问题描述】:

当从 NASDAQ 抓取数据时,有一些像 ACHC 这样的股票代码有空白页。 ACHC Empty Field

我的程序遍历所有股票代码,当我到达这个时它超时,因为没有数据可以掌握。我试图找出一种方法来检查是否没有任何内容,如果是,则跳过代码,但继续循环。代码很长,所以我会发布最相关的部分:打开页面的循环的开头:

## navigate to income statement annualy page    
url = url_form.format(symbol, "income-statement")
browser.get(url)

company_xpath = "//h1[contains(text(), 'Company Financials')]"
company = WebDriverWait(browser, 10).until(EC.presence_of_element_located((By.XPATH, company_xpath))).text

annuals_xpath = "//thead/tr[th[1][text() = 'Period Ending:']]/th[position()>=3]"
annuals = get_elements(browser,annuals_xpath)

Here is a pic of the error message

【问题讨论】:

    标签: python selenium debugging selenium-webdriver firebug


    【解决方案1】:

    Selenium 没有用于确定元素是否存在的内置方法,因此最常见的做法是使用 try/except 块。

    from selenium.common.exceptions import TimeoutException
    ...
    try:
        company = WebDriverWait(browser, 10).until(EC.presence_of_element_located((By.XPATH, company_xpath))).text
    except TimeoutException:
       continue
    

    假设 continue 在您的循环中按预期工作,这应该可以让循环继续运行而不会崩溃。

    【讨论】:

      【解决方案2】:

      您可以使用 requestsurllib 之类的库来抓取该网页并检查您需要的内容是否存在。这些库比 Selenium 快得多,因为它们只是获取页面的源代码。如果您正在寻找特定的标签或结构(如表格等),您应该查看beautifulsoup,您可以将其与requests 一起使用,以识别页面中非常具体的部分。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-03-31
        • 2017-03-23
        • 2013-07-06
        • 2023-03-29
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多