【问题标题】:How to properly close a Selenium WebDriver instance in python?如何在 python 中正确关闭 Selenium WebDriver 实例?
【发布时间】:2018-12-11 17:38:45
【问题描述】:

我正在编写一个脚本来检查代理是否正常工作。该计划应: 1. 从列表 (txt) 中加载代理。 2. 转到任何页面(例如维基百科) 3. 如果页面已经加载(甚至没有完全加载),它会将代理数据保存到另一个 txt 文件中。

它必须都在循环中。它还必须检查浏览器是否显示错误。我每次都关闭以前的浏览器时遇到问题,在几个循环之后,几个浏览器已经打开。

附言。我用随机数替换了迭代

from selenium import webdriver
import random
from configparser import ConfigParser
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
import traceback

while 1:
    ini = ConfigParser()
    ini.read('liczba_proxy.ini')

    random.random()
    liczba_losowa = random.randint(1, 999)

    f = open('user-agents.txt')
    lines = f.readlines()
    user_agent = lines[liczba_losowa]
    user_agent = str(user_agent)

    s = open('proxy_list.txt')
    proxy = s.readlines()

    i = ini.getint('liczba', 'liczba')

    prefs = {"profile.managed_default_content_settings.images": 2}
    chrome_options = webdriver.ChromeOptions()
    chrome_options.add_argument('--proxy-server=%s' % proxy[liczba_losowa])
    chrome_options.add_argument(f'user-agent={user_agent}')
    chrome_options.add_experimental_option("prefs", prefs)
    driver = webdriver.Chrome(chrome_options=chrome_options, executable_path='C:\Python\Driver\chromedriver.exe')
    driver.get('https://en.wikipedia.org/wiki/Replication_error_phenotype')

    def error_catching():
        print("error")
        driver.stop_client()
        traceback.print_stack()
        traceback.print_exc()
        return False


    def presence_of_element(driver, timeout=5):
        try:
            w = WebDriverWait(driver, timeout)
            w.until(EC.presence_of_element_located((By.ID, 'siteNotice')))
            print('work')
            driver.stop_client()
            return True
        except:
            print('not working')
            driver.stop_client()
            error_catching()

【问题讨论】:

    标签: python selenium web-scraping screen-scraping


    【解决方案1】:

    不评论你的代码设计:

    为了close a driver instance,请使用driver.close()driver.quit() 而不是您的driver.stop_client()

    第一个关闭设置焦点的浏览器窗口。 第二个基本上关闭了所有浏览器窗口并优雅地结束了 WebDriver 会话。

    【讨论】:

      【解决方案2】:

      使用

      chrome_options.quit()
      

      Obs.:我很确定你不应该使用这样的测试用例......“while 1”?所以你的测试永远不会结束?

      我想你应该在 TestCases 中设置你的测试并调用 TheSuite 来测试你所有的测试用例并给你一个关于是否通过的反馈,也许设置一个 cronjob 以不时地调用它。

      这是一个使用 django 和 splinter 测试用例的简单示例(splinter 构建在 selenium 之上)

      https://github.com/Diegow3b/python-django-basictestcase/blob/master/myApp/tests/test_views.py

      【讨论】:

        猜你喜欢
        • 2022-10-07
        • 1970-01-01
        • 2020-10-22
        • 2017-07-24
        • 2018-03-09
        • 1970-01-01
        • 2021-09-17
        • 1970-01-01
        • 2014-12-13
        相关资源
        最近更新 更多