【问题标题】:Can't let a script run at regular intervals不能让脚本定期运行
【发布时间】:2020-05-05 18:51:26
【问题描述】:

我正在尝试以某种方式修改以下脚本,以便它可以定期运行。我知道如何使用请求来做同样的事情。但是,如果是硒,我就卡住了。

我试过了

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

link = 'https://stackoverflow.com/questions/tagged/web-scraping'

def get_content(link):
    driver.get(link)
    for item in WebDriverWait(driver,10).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR,".question-summary"))):
        title = item.find_element_by_css_selector(".question-hyperlink").text
        link = item.find_element_by_css_selector(".question-hyperlink").get_attribute("href")
        print(title,link)
    driver.quit()

if __name__ == '__main__':
    driver = webdriver.Chrome()
    while True:
        get_content(link)
        time.sleep(20)

如何让脚本定期运行?

如果我按原样运行,我会在第二次尝试时收到以下错误:

    raise MaxRetryError(_pool, url, error or ResponseError(cause))
urllib3.exceptions.MaxRetryError: HTTPConnectionPool(host='127.0.0.1', port=51356): Max retries exceeded with url: /session/41bae2407c029ad2879619c3e65552da/url (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x02504850>: Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it'))

【问题讨论】:

  • 基于错误,您的目标服务器拒绝连接。
  • 无论我选择哪个站点,脚本都会遇到相同的错误,所以我想我创建脚本的方式有问题。
  • 我认为你不应该在你的函数中调用 driver.quit() 。在 while True 循环之后,您实际上并不想退出驱动程序。

标签: python python-3.x selenium selenium-webdriver web-scraping


【解决方案1】:

Fn: 获取内容;使用 driver.quit。

所以,最终它关闭了驱动程序。这意味着,在下一次运行中,您需要一个新的 Web 驱动程序实例。

def get_content(link, driver):
    driver.get(link)
    ... .. .
    driver.quit()

if __name__ == '__main__':
    while True:
        driver = webdriver.Chrome()
        get_content(link, driver)
        time.sleep(20)

【讨论】:

    猜你喜欢
    • 2018-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多