如果我从实例中调用它,driver.close()不会关闭selenium上的选项卡

时间:2018-06-14 07:20:59

标签: python selenium

我想关闭从Selenium打开的Chrome上的标签,但如果我创建了一个实例并从实例调用driver.close(),则它不会关闭标签。例如,

class Download:

    def __init__(self, word, driver):
        self.word = word
        self.word_url = word_url_meta.format(word)
        self.driver = driver


    def close_tab(self):
        self.switch_window(self.current_window)
        time.sleep(0.2)
        self.driver.close()
        time.sleep(0.2)
        self.switch_window(self.driver.window_handles[-1])

    def switch_window(self):  
        time.sleep(0.2) 
        self.driver.switch_to_window(self.current_window) 

然后,我称之为:

w = Download()
w.do_something()
w.close_tab()

如果我从顶层调用它,标签会正常关闭。但是当我从实例方法调用它时,选项卡不会关闭。

为什么它会阻止标签关闭?我怎样才能正确关闭它?

修改

现在我可能想知道是因为用asyncio包裹它。

async def download_word(word, driver, semaphore):
    async with semaphore:
        w = Download(word, driver)
        w.open_new_tab()
        await w.check_if_downloadable()
        await w.download()
        w.close_tab()

async def main():
    asyncio_semaphore = asyncio.BoundedSemaphore(2)
    jobs = []
    for i in range(4):
        jobs.append(asyncio.ensure_future(download_word(words[i], driver, asyncio_semaphore)))
    await asyncio.gather(*jobs)

loop.run_until_complete(main())

这里有用吗?

1 个答案:

答案 0 :(得分:0)

我不认为你做错了什么。只是稍微修改了你的代码,它对我有用:

word = None
import time

class Download:

    def __init__(self, word, driver):
        self.word = word
        self.driver = driver
        self.driver.get(word)     
        time.sleep(2)
        self.driver.execute_script("window.open('" + word + "', 'new_window')")
        time.sleep(2)

    def close_tab(self):
        self.driver.close()
        time.sleep(2)

测试:

class TestCloseTab:    

    def test_close_tab(self):
        download = Download('http://testjs.site88.net/', pytest.driver)
        download.close_tab()