python-3.x - 如何在打开下一个新标签之前关闭硒中自动打开的标签?
问题描述
在页面中收集各种链接后,我单击它们并将其收集到汤中。现在的问题是,链接在新选项卡中打开。我想在代码在新选项卡中打开下一个链接之前关闭选项卡。下面是代码片段。收集汤后请帮我关闭每个标签。
我使用 python 3.7 selenium chromedriver
# collecting results from page 1 only.
candidate_name = []
candidate_links = driver.find_elements_by_xpath("//a[@data-tn-element='resume-result-link[]']")
for candidates in candidate_links:
candidate_name.append(candidates.text)
candidates.click()
time.sleep(3)
html_content = driver.page_source
soup = BeautifulSoup(html_content, 'html.parser')
text = soup.getText()
candidates.send_keys(Keys.CONTROL+'w')
#write it to a text file
for i in candidate_name:
path = r'c:/users/user/desktop/resumes1/'+ i
with open(path, 'w', encoding='utf-8') as file:
file.write(text)
time.sleep(5)
assert "No results found." not in driver.page_source
driver.quit()
解决方案
简单的代码对我有用,如下所示。在打开下一个选项卡之前关闭选项卡。
# switch to the tab
driver.switch_to.window(driver.window_handles[-1])
# do whatever in the tab
time.sleep(5)
# close the tab
driver.close()
#switch back to the main window again
driver.switch_to.window(driver.window_handles[0])
推荐阅读
- javascript - 通过 JavaScript 设置 HTML 元素的 CSS 宽度
- java - 错误:未指定模块,但没有输入模块的字段
- docker - Docker 提交用法
- javascript - 当屏幕大小低于断点时将类附加到 div
- flutter - 在 Streambuilder 中合并两个流并返回一个 ListView (Flutter)
- javascript - Chrome 扩展 - 从清单 v2 迁移到 v3
- python - selenium 中的 self.start_error_message)
- mysql - Mysql查询从多条记录中获取最低字段值
- bash - 如何匹配文本文件中的字符?
- php - 如何在 PHP 中验证图像 URL 的尺寸和格式?