简体   繁体   中英

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)

在此输入图像描述

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM