0

So I'm trying to open a new tab on Chrome where the URL is a string. I'm doing it this way because neither Action Chains or Keys seem to work. The purpose of this code is to open a new tab from a selected element but I can't seem to open a new page with the correct website.

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

chromedriver = "\Program Files\webdrivers/chromedriver"

driver = webdriver.Chrome(chromedriver)

driver.get("https://google.com")

time.sleep(3)

for a in driver.find_elements_by_xpath('//*[@id="prm"]/div/a'):
    A = str(a.get_attribute('href'))
    driver.execute_script("window.open('A');")
2
  • Is the xpath correct for the given url [google.com]? could not locate any such locator. Commented Nov 15, 2018 at 19:25
  • It is from the dutch google website but you can use any valid xpath. I just looking to make it work Commented Nov 15, 2018 at 20:18

2 Answers 2

1

You are opening a new window with the URL of 'A'. It's being treated as a string because you aren't passing in the variable, just a letter. Try

driver.execute_script("window.open(arguments[0]);", A)
Sign up to request clarification or add additional context in comments.

1 Comment

I accidentally left in the single quotes around arguments[0]. I've updated the answer... it works now.
0

To open the hrefs in seperate TABs the correct syntax would be:

for a in driver.find_elements_by_xpath('//*[@id="prm"]/div/a'):
    A = str(a.get_attribute('href'))
    driver.execute_script("window.open('" + A +"');")

2 Comments

Is there a way to close that same tab and return to the initial? This is, without closing the whole browser?
@LourençoSaint-Maurice Of-coarse there is a much cleaner way to close the newly opened tab and retain focus on the initial tab without closing the whole browser.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.