0

I am trying to scrape a webpage that opens up hyperlinks via javascript as shown below. I am using Selenium with Python.

<a href="javascript:openlink('120000020846')">
<subtitle>Blah blah blah</subtitle>
</a>

Using XPATH, I was able to open up the hyperlink using the following Python code.

driver = webdriver.Chrome()
xpath = '//a/subtitle[contains(text(),"Blah blah blah")]'
link_to_open = driver.find_element(By.XPATH,xpath);
link_to_open.click()

However, the link opens in the same tab. This is not what I want, as I want the links to open in a new tab, so that I can retain the information of the current page and continue processing the rest of the links.

Would greatly appreciate if anyone can give me some pointers if this can be done?

Thank you so much! :)

JeffC
  • 22,180
  • 5
  • 32
  • 55
Dora Chua
  • 23
  • 2
  • Possible duplicate of [Open web in new tab Selenium + Python](https://stackoverflow.com/questions/28431765/open-web-in-new-tab-selenium-python) – Nico Albers Apr 01 '18 at 17:21
  • 1
    Possible duplicate of [What is the fastest way to open urls in new tabs via Selenium - Python?](https://stackoverflow.com/questions/47543795/what-is-the-fastest-way-to-open-urls-in-new-tabs-via-selenium-python) – undetected Selenium Apr 01 '18 at 21:18
  • Hi my question is different from the so-called 'duplicate' ones. My links are javascript already. By default, even if a human clicks on a javascript link, he cannot open it in a new tab. I want to know if there is any workaround for this? I already know how to open links in a new tab with normal hyperlinks (ie. Those without javascript) – Dora Chua Apr 02 '18 at 00:16

1 Answers1

0

You can force a link to open in a new tab through the ActionChains implementation as follows :

from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys

action = ActionChains(driver)
link_to_open = driver.find_element(By.XPATH, "//a/subtitle[contains(.,'Blah blah blah')]")
action.key_down(Keys.CONTROL).click(link_to_open).key_up(Keys.CONTROL).perform()
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352