简体   繁体   中英

executing Javascript using Selenium in python (Tkinter as GUI)

hi i am opening a website using selenium webdriver from a tkinter GUI.i have a entry and a button in gui when ever i give the url in entry and press the button the web browser starts opening now i want to add another functionality that if i select any text on that webpage using my mouse cursor and press another button again on GUI it should show the selected text in some other entry area in the tkinter GUI. So, Is it possible to add this functionality. here is my code:-

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) 

The root cause is your web site doesn't have method getSelectionText() . You can add then call it, see code below:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM