Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 504
Kiran Avatar asked May 30 '18 12:05

Kiran


People also ask

How do I stop a loading page in Selenium?

Selenium can execute JavaScript commands with the help of the executeScript command. To stop a page loading, the command window. stop() is passed as a parameter to the executeScript method.

How do you close a tab in python Selenium?

close tab is Command + 'w'.

How do I stop pop ups in Selenium Python?

To dismiss a popup, the method switch_to. alert(). dismiss() is used.


1 Answers

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)
like image 154
Andersson Avatar answered Oct 23 '22 04:10

Andersson