selenium 问题:OSError: [WinError 6] 句柄无效
解决方案:
关闭driver 时 , 使用 driver.quit()代替 driver.close()。
分析:
之前使用 driver.close() 时,用例执行结束有时会不能成功关闭chromedriver.exe,导致后台含有多个chromedriver.exe 进程(可以通过任务管理器查看)。
改用 driver.quit()之后,用例执行结束可以看到后台不会含有 chromedriver.exe 进程。该问题就解决了。
备注:区别
close:只会关闭焦点所在的当前窗口
quit:会关闭所有关联的窗口
所以推荐使用quit 。
def get_url(url):
driver = webdriver.Chrome(
executable_path="C:\Program Files (x86)\Google\Chrome\Application\chromedriver")
driver.get(url) # 获取网页
time.sleep(3)
page = driver.page_source
doc = etree.HTML(str(page))
# print(tostring(doc, encoding='utf-8').decode('utf-8'))
group_url_list = doc.xpath("//div[@class='title-box']/a/@href")
group_url = []
for u in group_url_list:
group = "https://www.toutiao.com" + u
group_url.append(group)
print(group_url)
driver.quit()
return group_url