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 Answers2

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)
JeffC
  • 22,180
  • 5
  • 32
  • 55
  • I accidentally left in the single quotes around `arguments[0]`. I've updated the answer... it works now. – JeffC Nov 15 '18 at 23:56
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 +"');")
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352