首页 > 解决方案 > 如何在打开下一个新标签之前关闭硒中自动打开的标签?

问题描述

在页面中收集各种链接后,我单击它们并将其收集到汤中。现在的问题是,链接在新选项卡中打开。我想在代码在新选项卡中打开下一个链接之前关闭选项卡。下面是代码片段。收集汤后请帮我关闭每个标签。

我使用 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()

标签: python-3.xselenium-chromedriver

解决方案


简单的代码对我有用,如下所示。在打开下一个选项卡之前关闭选项卡。

# 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])

推荐阅读