Reputation: 151
Upon collecting various links in a page, i click on those and collect it into a soup. Now the issue is, links are opened in a new tab. I want to close the tab before the code opens the next link in a new tab. Below is the code snippet. Please help me to close each tab after collecting the soup.
I use 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()
Upvotes: 0
Views: 762
Reputation: 151
Simple code worked for me as below. Closed the tabs before opening the next one.
# 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])
Upvotes: 1