Hướng dẫn python selenium open new tab and switch to it - python Selenium mở tab mới và chuyển sang tab đó

Đây là toàn bộ kịch bản.

Lưu ý: Tháo các khoảng trắng trong hai dòng cho URL nhỏ bên dưới.Stack Overflow không cho phép liên kết nhỏ ở đây. Remove the spaces in the two lines for tiny URL below. Stack Overflow does not allow the tiny link in here.

import ahk
import win32clipboard
import traceback
import appJar
import requests
import sys
import urllib
import selenium
import getpass
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import socket
import time 
import urllib.request
from ahk import AHK, Hotkey, ActionChain # You want to play with AHK. 
from appJar import gui

try:                                                                                                                                                                         
    ahk = AHK(executable_path="C:\\Program Files\\AutoHotkey\\AutoHotkeyU64.exe")    

except:                                                                                                                                                                         
    ahk = AHK(executable_path="C:\\Program Files\\AutoHotkey\\AutoHotkeyU32.exe")    

finally:                                                                                                                                                                         
    pass 

chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--start-maximized')
chrome_options.add_experimental_option("excludeSwitches", ['enable-automation']);
chromeDriver = webdriver.Chrome('C:\\new_software\\chromedriver.exe', chrome_options = chrome_options)

def  ahk_disabledevmodescript():
    try:                                                                                                                                                                         
        ahk = AHK(executable_path="C:\\Program Files\\AutoHotkey\\AutoHotkeyU64.exe")                                                                                                                                                                           
    except:                                                                                                                                                                         
        ahk = AHK(executable_path="C:\\Program Files\\AutoHotkey\\AutoHotkeyU32.exe")                                                                                                                                                                         
    finally:                                                                                                                                                                         
        pass   
    ahk_disabledevmodescriptt= [
    str('WinActivate,ahk_exe chrome.exe'),
    str('Send {esc}'),
    ]
    #Run-Script
    for snipet in  ahk_disabledevmodescriptt:
        ahk.run_script(snipet, blocking=True )
    return 

def launchtabsagain():

    chromeDriver.execute_script("window.open('https://developers.google.com/edu/python/introduction', 'tab2');")
    chromeDriver.execute_script("window.open('https://www.facebook.com/', 'tab3');")
    chromeDriver.execute_script("window.open('https://developer.mozilla.org/en-US/docs/Web/API/Window/open', 'tab4');")
    chromeDriver.execute_script("window.open('https://www.easyespanol.org/', 'tab5');")
    chromeDriver.execute_script("window.open('https://www.google.com/search?source=hp&ei=EPO2Xf3EMLPc9AO07b2gAw&q=programming+is+not+difficult&oq=programming+is+not+difficult&gs_l=psy-ab.3..0i22i30.3497.22282..22555...9.0..0.219.3981.21j16j1......0....1..gws-wiz.....6..0i362i308i154i357j0j0i131j0i10j33i22i29i30..10001%3A0%2C154.h2w5MmbFx7c&ved=0ahUKEwj9jIyzjb_lAhUzLn0KHbR2DzQQ4dUDCAg&uact=5', 'tab6');")
    chromeDriver.execute_script("window.open('https://www.google.com/search?source=hp&ei=NvO2XdCrIMHg9APduYzQDA&q=dinner+recipes&oq=&gs_l=psy-ab.1.0.0i362i308i154i357l6.0.0..3736...0.0..0.179.179.0j1......0......gws-wiz.....6....10001%3A0%2C154.gsoCDxw8cyU', 'tab7');")

    return  
chromeDriver.get('https://ebc.cybersource.com/ebc2/')
compoanionWindow = ahk.active_window

launchtabs = launchtabsagain()
disabledevexetmessage = ahk_disabledevmodescript()



def copyUrl(): 
    try:                                                                                                                                                                         
        ahk = AHK(executable_path="C:\\Program Files\\AutoHotkey\\AutoHotkeyU64.exe")                                                                                                                                                                           
    except:                                                                                                                                                                         
        ahk = AHK(executable_path="C:\\Program Files\\AutoHotkey\\AutoHotkeyU32.exe")                                                                                                                                                                         
    finally:                                                                                                             

        pass 
    snipet = str('WinActivate,ahk_exe chrome.exe')
    ahk.run_script(snipet, blocking=True )  
    compoanionWindow.activate() 
    ahk_TinyChromeCopyURLScript=[

        str('WinActivate,ahk_exe chrome.exe'),
        str('send ^l'),
        str('sleep 10'),
        str('send ^c'),
        str('BlockInput, MouseMoveoff'),
        str('clipwait'),
    ] 

    #Run-AHK Script
    if ahk:
        for snipet in  ahk_TinyChromeCopyURLScript:
            ahk.run_script(snipet, blocking=True )  
    win32clipboard.OpenClipboard()
    urlToShorten = win32clipboard.GetClipboardData()
    win32clipboard.CloseClipboard()   


    return(urlToShorten)


def tiny_url(url):
    try:

        apiurl = "https: // tinyurl. com / api - create. php? url= " #remove spaces here
        tinyp = requests.Session()
        tinyp.proxies = {"https" : "https://USER:PASSWORD." + "@userproxy.visa.com:443", "http" : "http://USER:PASSWORD." + "@userproxy.visa.com:8080"}
        tinyUrl = tinyp.get(apiurl+url).text
        returnedresponse = tinyp.get(apiurl+url)
        if returnedresponse.status_code == 200: 
            print('Success! response code =' + str(returnedresponse))
        else:
            print('Code returned = ' + str(returnedresponse))
            print('From IP Address =' +IPadd)


    except:
        apiurl = "https: // tinyurl. com / api - create. php? url= " #remove spaces here
        tinyp = requests.Session()
        tinyUrl = tinyp.get(apiurl+url).text
        returnedresponse = tinyp.get(apiurl+url)
        if returnedresponse.status_code == 200: 
            print('Success! response code =' + str(returnedresponse))
            print('From IP Address =' +IPadd)
        else:
            print('Code returned = ' + str(returnedresponse))

    return tinyUrl

def tinyUrlButton():

    longUrl = copyUrl()
    try:                                                                                                                                                                         
        ahk = AHK(executable_path="C:\\Program Files\\AutoHotkey\\AutoHotkeyU64.exe")                                                                                                                                                                           
    except:                                                                                                                                                                         
        ahk = AHK(executable_path="C:\\Program Files\\AutoHotkey\\AutoHotkeyU32.exe")                                                                                                                                                                         
    finally:                                                                                                                                                                         
        pass
    try:
        shortUrl = tiny_url(longUrl)
        win32clipboard.OpenClipboard()
        win32clipboard.EmptyClipboard()
        win32clipboard.SetClipboardText(shortUrl)
        win32clipboard.CloseClipboard()
        if ahk:
            try:
                if str(shortUrl) == 'Error':
                    ahk.run_script("Msgbox,262144 ,Done.,"+ shortUrl + "`rPlease make sure there is a link to copy and that the page is fully loaded., 5.5" )
                else:
                    ahk.run_script("Msgbox,262144 ,Done.,"+ shortUrl + " is in your clipboard., 1.5" )
                # ahk.run_script("WinActivate, tinyUrl" )
            except:
                traceback.print_exc()
                print('error during ahk script')

                pass

    except:
        print('Error getting tinyURl')
        traceback.print_exc()

def closeChromeTabs(): 
        try: 
            try:                                                                                                                                                                          
                ahk = AHK(executable_path="C:\\Program Files\\AutoHotkey\\AutoHotkeyU64.exe")                                                                                                                                                                          
            except:                                                                                                                                                                          
                ahk = AHK(executable_path="C:\\Program Files\\AutoHotkey\\AutoHotkeyU32.exe")                                                                                                                                                                  
            finally:                                                                                                                                                                          
                    pass   
            compoanionWindow.activate()  
            ahk_CloseChromeOtherTabsScript = [ 

                str('WinActivate,ahk_exe chrome.exe'), 
                str('Mouseclick, Right, 30, 25,,1'), 
                str('Send {UP 3} {enter}'), 
                str('BlockInput, MouseMoveOff'), 
                ] 
                #Run-Script 
            if ahk: 
                for snipet in  ahk_CloseChromeOtherTabsScript: 
                        ahk.run_script(snipet, blocking=True ) 
            return(True) 
        except: 
            traceback.print_exc() 
            print("Failed to run closeTabs function.") 
            ahk.run_script('Msgbox,262144,,Failed to run closeTabs function.,2') 
            return(False)         



        # create a GUI and testing this library.

window = gui("tinyUrl and close Tabs test ", "200x160")
window.setFont(9)
window.setBg("blue")
window.removeToolbar(hide=True)
window.addLabel("description", "Testing AHK Library.")
window.addLabel("title", "tinyURL")
window.setLabelBg("title", "blue")
window.setLabelFg("title", "white")
window.addButtons(["T"], tinyUrlButton)
window.addLabel("title1", "Close tabs")
window.setLabelBg("title1", "blue")
window.setLabelFg("title1", "white")
window.addButtons(["C"], closeChromeTabs)
window.addLabel("title2", "Launch tabs")
window.setLabelBg("title2", "blue")
window.setLabelFg("title2", "white")
window.addButtons(["L"], launchtabsagain)
window.go()

if window.exitFullscreen():
    chromeDriver.quit()


def closeTabs():
    try:
        try:                                                                                                                                                                         
            ahk = AHK(executable_path="C:\\Program Files\\AutoHotkey\\AutoHotkeyU64.exe")                                                                                                                                                                           
        except:                                                                                                                                                                         
            ahk = AHK(executable_path="C:\\Program Files\\AutoHotkey\\AutoHotkeyU32.exe")                                                                                                                                                                         
        finally:                                                                                                                                                                         
                pass   

        compoanionWindow.activate()     
        ahk_CloseChromeOtherTabsScript = [

            str('WinActivate,ahk_exe chrome.exe'),
            str('Mouseclick, Right, 30, 25,,1'),
            str('Send {UP 3} {enter}'),
            str('BlockInput, MouseMoveOff'),
            ]
            #Run-Script
        if ahk:
            for snipet in  ahk_CloseChromeOtherTabsScript:
                    ahk.run_script(snipet, blocking=True )
        return(True)
    except:
        traceback.print_exc()
        print("Failed to run closeTabs function.")
        ahk.run_script('Msgbox,262144,Failed,Failed to run closeTabs function.,2')
        return(False)

Chúng ta có thể chuyển đổi tab trong selen không?

Chúng ta có thể chuyển đổi các tab bằng selen.Đầu tiên chúng ta phải mở một liên kết trong một tab mới.Những chiếc chìa khóa.Phương pháp hợp âm cùng với SendKeys sẽ được sử dụng.. First we have to open a link in a new tab. The Keys. chord method along with sendKeys is to be used.

Làm thế nào bạn có thể chuyển sang một cửa sổ mới trong selenium?

Nhận tay cầm của tất cả các cửa sổ hiện đang mở bằng lệnh: Đặt AllWindowHandles = Driver.getWindowHandles ();mà trả về bộ tay cầm.Sử dụng lệnh Switchto để chuyển sang cửa sổ mong muốn và cũng vượt qua URL của trang web.Use the SwitchTo command to switch to the desired window and also pass the URL of the web page.

Selenium hoạt động như thế nào với nhiều tab trong Python?

Các bước được yêu cầu: Nó phải được đặt trong biến đường dẫn trên đường dẫn trong Windows và cả trong Linux và Mac, ở các vị trí tương ứng, nó phải được đặt.Mở một trình duyệt Firefox mới từ Python.Sau đó tải trang tại URL hợp lệ đã cho.