【发布时间】: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