在收集页面中的各种链接后,我单击这些链接并将其收集到汤中。现在的问题是,链接在新选项卡中打开。我想在代码打开新标签中的下一个链接之前关闭标签。下面是代码片段。请帮我收集汤后关闭每个标签。
我使用python 3.7硒驱动程序
# 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()
答案 0 :(得分:0)
简单的代码对我有用,如下所示。在打开下一个选项卡之前,请先关闭这些选项卡。
# 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])