簡體   English   中英

在python中使用Selenium執行Javascript(Tkinter作為GUI)

[英]executing Javascript using Selenium in python (Tkinter as GUI)

嗨,我從tkinter GUI使用selenium webdriver打開一個網站。當我輸入url時,我在gui中有一個條目和一個按鈕,然后按下該按鈕,網絡瀏覽器現在開始打開。我想添加另一個功能,如果我使用鼠標光標在該網頁上選擇任何文本,然后再次在GUI上按另一個按鈕,它將在tkinter GUI的其他輸入區域中顯示所選文本。 因此,是否可以添加此功能。 這是我的代碼:-

url1 = Entry(top, bd =3, width = 50)
url1.place(x=800 , y=100)

def open(url):
    driver = webdriver.Firefox()
    driver.set_window_size(600, 500)
    driver.set_window_position(300,300)
    driver.get(url)
    driver.implicitly_wait(20)
    driver.execute_script("text = getSelectionText(); alert(text)")

# submit button which is performing action on submit
submit1 = Button(top, text="Open", width=15, bg='lightblue', command=lambda: open(url1.get()))
submit1.place(x=1200, y=100) 

根本原因是您的網站沒有方法getSelectionText() 您可以添加然后調用它,請參見下面的代碼:

jsScript = '''
function getSelectionText() {
    var text = "";
    if (window.getSelection) {
        text = window.getSelection().toString();
    } else if (document.selection && document.selection.type != "Control") {
        text = document.selection.createRange().text;
    }
    return text;
}

text = getSelectionText(); alert(text)
'''

driver.execute_script(jsScript)

暫無
暫無

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

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