python - 我们如何在循环中创建 selenium webdriver 对象并在循环结束后关闭窗口?

标签 python python-3.x selenium selenium-webdriver sleep

因此,我尝试打开列表中的每个链接(通过 for 循环运行)并对该链接执行一些操作。

我想为循环中的每个链接打开一个窗口,对其进行操作,关闭它,然后重新开始循环。

for link in links_list:
    driver = webdriver.Chrome('D:/location-of-driver.exe')
    driver.implicitly_wait(5)

    driver.get(link)

    a_variable = driver.find_element_by_css_selector('selector')

    time.sleep(3)  # required for my usage

    driver.close()  # this I believe should close the window

因此循环迭代 1 次并在再次到达顶部时崩溃。 driver.close() 适用于第一次迭代

我希望包含当前链接的窗口打开 3 秒,然后循环重新开始。

错误:

Traceback (most recent call last):
  File "./play.py", line 18, in <module>
    driver.get(link)
selenium.common.exceptions.WebDriverException: Message: invalid session id
(Driver info: chromedriver=2.45.615291 
(ec3682e3c9061c10f26ea9e5cdcf3c53f3f74387),platform=Windows NT 10.0.17134 
x86_64)

提前致谢!

最佳答案

@Gaurav 正如所讨论的,请尝试这个。如果您遇到类似的问题,那么我相信您已将 chrome 驱动程序更新到最新版本。

links_list = ["https://www.google.com/", "https://www.w3schools.com/","https://www.toolsqa.com/"]

for link in links_list:
    driver = webdriver.Chrome('D:/Java/TestChrome/lib/chromedriver.exe')
    driver.implicitly_wait(5)
    print(link)
    driver.get(link)

   # a_variable = driver.find_element_by_css_selector('selector')

    time.sleep(3)  # required for my usage

    #driver.quit()  # this I believe should close the window
    driver.close()

print('pass')

关于python - 我们如何在循环中创建 selenium webdriver 对象并在循环结束后关闭窗口?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54368160/

相关文章:

python - Python 的 SQLAlchemy 是否支持服务器端游标(对于 MSSQL)?

python - 如果 SetUpClass 中的某些条件失败,则跳过单元测试

python - Git tree-filter 在提交时运行 python 脚本

python - 如何调试导致连接被拒绝或连接超时的原因?

python - Pandas检查IP地址属于哪个子网

python - 使用python在打开的cv中使用鼠标事件绘制矩形或线

java - Selenium Webdriver java 自动化窗口

multithreading - selenium 线程可以安全地使用 Python 进行抓取吗?

python - Selenium get_attribute

python - 如何使用 SOAPpy 创建非标准类型?