python selenium how positioning elements of the site and click on the graph carousel

Take Mu class network for example, using the knowledge of multi-window switching.
Note: when positioning, to set the wait time, wait for it to load elements.

```python
#点击链接以及轮播图图片点击
from selenium import webdriver
from time import sleep
driver=webdriver.Firefox()
driver.get("https://www.baidu.com/")
#在输入框输入内容
driver.find_element(By.ID, "kw").send_keys("慕课网")
#定位百度一下按钮
driver.find_element(By.ID, "su").click()
sleep(2)
#获取当前窗口句柄
h1=driver.current_window_handle
print("当前句柄:",h1)
print("当前页面的标题:",driver.title)
print("当前页面的url:",driver.current_url)
sleep(1)
#点击慕课网链接
driver.find_element(By.LINK_TEXT, "慕课网-程序员的梦工厂").click()
sleep(4)
#获取当前打开的窗口所有句柄
all_had=driver.window_handles
print("所有句炳:",all_had)
#使用for循环切换窗口,获取新打开到窗口句柄
for i in all_had:
    if i!=h1:
        #切换到指定句柄窗口
        driver.switch_to.window(i)
        h2=driver.current_window_handle
        print("当前句柄2:",h2)
        print("当前页面的标题:", driver.title)
        print("当前页面的URL:", driver.current_url)
        sleep(2)
        #定位第一张轮播图并点击
        driver.find_element(By.XPATH,"//*[@id='main']/div[2]/div[1]/div[10]/div/a[1]/div/img").click()
        sleep(2)
        driver.close()#关闭当前窗口
        

Results of Here Insert Picture Description
multi-window switching step:
The first step: get the current window handle
h1 = driver.current_window_handle
Step: Get all currently open window handles
all_had = driver.window_handles
third step: # switch to the specified window handle
driver.switch_to. window (h1)

Released four original articles · won praise 5 · Views 441

Guess you like

Origin blog.csdn.net/qq_39878747/article/details/104360358