Kiran
Kiran

Reputation: 8538

How to disable opening the page in a new tab in Selenium Webdriver in Python?

I am scraping the site : http://www.delhidistrictcourts.nic.in/DLCIS-2016-2.html

There are a number of links in this page. The user would click on any of these links ( via selenium web driver). The problem is, when the user clicks on these links, it opens in a new tab because all the links has an attribute ( "_target=blank")

Any idea how to force, the links to open in the same tab ?

Here is the code I have written

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
url = 'http://www.delhicourts.nic.in/DLCIS-2016-2.html'

driver=webdriver.Chrome()
driver = webdriver.Chrome()
wait = WebDriverWait(driver, 10)
driver.get(url)

try:
    wait.until(EC.presence_of_element_located((By.CLASS_NAME, "submit1"))).click()
except Exception as e:
    print str(e)

enter image description here

Upvotes: 7

Views: 7011

Answers (1)

Andersson
Andersson

Reputation: 52685

You can try to update the value of @target:

link = wait.until(EC.presence_of_element_located((By.LINK_TEXT, "CASE NUMBER WISE")))
driver.execute_script("arguments[0].target='_self';", link)
link.click()

To apply the same for all the links on page:

links = wait.until(EC.presence_of_all_elements_located((By.TAG_NAME, "a")))
for link in links:
    driver.execute_script("arguments[0].target='_self';", link)

or extract @href of link and get() it:

link = wait.until(EC.presence_of_element_located((By.LINK_TEXT, "CASE NUMBER WISE")))
url = link.get_attribute('href')
driver.get(url)

Upvotes: 7

Related Questions