从字符串u打开新选项卡

2024-06-02 09:22:07 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我试着在Chrome上打开一个新的标签,其中URL是一个字符串。我这样做是因为动作链和键似乎都不起作用。此代码的目的是从所选元素打开一个新选项卡,但我似乎无法使用正确的网站打开一个新页面。你知道吗

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');")

Tags: 字符串fromimporturlgettimedriverselenium
2条回答

要在单独的选项卡中打开hrefs,正确的语法是:

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

您正在打开一个URL为“a”的新窗口。它被视为一个字符串,因为您没有传递变量,只是传递一个字母。试试看

driver.execute_script("window.open(arguments[0]);", A)

相关问题 更多 >