簡體   English   中英

使用可變鏈接在瀏覽器中打開選項卡

[英]Opening tabs in browser with a variable link

我使用 python 和 selenium,試圖打開一個新標簽。 send_keys 函數不會打開選項卡,但 execute_script 會打開。 我的問題是我有一個保存在變量中的 url,我需要將它傳遞到腳本中,但出現錯誤。

代碼:

src = 'http://yahoo.com'
driver.execute_script("window.open(" + src + ",'_blank');")

錯誤信息:

selenium.common.exceptions.WebDriverException: Message: unknown error: Runtime.evaluate threw exception: SyntaxError: missing ) after argument list

也試過了,不行:

driver.find_element_by_tag_name('body').send_keys(Keys.COMMAND + 't')

driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + 't')

確實有效,但 url 是硬編碼的:

driver.execute_script("window.open('http://www.google.com/','_blank');")

您可以使用format來插入變量。

一個例子:

driver = webdriver.Chrome(executable_path="/tmp/chromedriver")

link = 'http://example.com'
driver.execute_script('window.open("{}","_blank");'.format(link))
driver.switch_to.window(driver.window_handles[-1])

這有效:

driver.execute_script('''window.open('',"_blank");''')
driver.switch_to.window(driver.window_handles[-1])
driver.get(src)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM