Getting started with python selenium automation: find, enter and click

Preliminary work:

Google browser: Download the Google browser driver. After downloading the driver, place it in the same path as the python.exe file.

python environment: python3+selenium4

Main topic:

The code is as follows. Use xpath to find elements. The process of finding elements uses display waiting and the timeout is set to 10s.

import time

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait

def find_element(driver,a):
    # 10s内每隔1s循环查询一次元素,找到元素返回元素本身,找不到抛超时异常
    element = WebDriverWait(driver,10,1).until(lambda x:x.find_element(By.XPATH,a))
    return element

if __name__ == '__main__':
    # 忽略https认证
    options = webdriver.ChromeOptions()
    options.add_argument('--ignore-certificate-errors')
    #新增浏览器驱动对象,可用来捕捉、操作浏览器元素
    driver = webdriver.Chrome(options=options)
    driver.get('https://10.87.13.10')
    #捕捉登录框,输入账号
    element_xpath ="//*[@id='container']/div[3]/div[3]/table/tbody/tr/td/div[2]/form/div[1]/div[1]/div/input"
    find_element(driver,element_xpath).send_keys('admin')
    # 捕捉密码框,输入密码
    element_xpath ="//*[@id='container']/div[3]/div[3]/table/tbody/tr/td/div[2]/form/div[1]/div[2]/div/input"
    find_element(driver,element_xpath).send_keys('test@12345')
    #捕捉登录按钮,点击登录
    element_xpath ="//*[@id='container']/div[3]/div[3]/table/tbody/tr/td/div[2]/form/button"
    find_element(driver,element_xpath).click()

    #关闭浏览器窗口
    time.sleep(10)
    driver.close()


The xpath path can be copied directly after Google browser f12:

Select the corresponding element row of elements, right-click-copy-copy Xpath

Dividing line: 20230220

Today, I was searching for an element on a page. After the text content of the element was output, it was always an empty string. Originally, I wanted to judge whether the page access was successful by comparing the text content, but it is currently stuck, and the reason is unclear (sometimes the text output of the element is normal, and sometimes the space-time string is output);

Temporary backup solution:

if "text" in driver.page_source: then the page access is considered successful;

Guess you like

Origin blog.csdn.net/Mr_wilson_liu/article/details/128950362