[Automated testing] selenium basic tutorial - environment construction & basic operation

1. Preliminary preparation

2. Basic operation

1. Instantiate a browser object

2. Enter URL

3. Positioning Elements and Interactions

4. Back, Forward and Close


1. Preliminary preparation

1. Install the selenium package, (provided that the python environment has been installed)

By default, the latest version is installed. If you want to install a specified version, bring the version number, such as pip install selenium==3.12.0

pip install selenium

2. Download the browser driver

Take the chrome browser as an example, download the corresponding browser driver, pay attention to the driver must match the browser version,

For the browser version, click the three dots in the upper right corner of chrome—help—you can check about chrome

Webdriver download address:

Chrome driver Taobao mirror download address  (recommended)

Chrome driver official website download address

3. Unzip the downloaded driver to the python root directory (you can also unzip it to other directories, and you need to bring the path when instantiating the browser object)

2. Basic operation

1. Instantiate a browser object

from selenium import webdriver 
# 实例化一个浏览器对象(传入浏览器的驱动程序)
driver = webdriver.Chrome()
#驱动程序不是和python同目录的话,需指定路径,如:
#driver = webdriver.Chrome(executable_path="D:/Program Files/test/chromedriver.exe")

2. Enter URL

url = "https://www.jd.com"
driver.get(url)  #打开jd网站

3. Positioning Elements and Interactions

Here we take the search box as an example, get its id, and use find_element_by_id() to locate it.

input = driver.find_element_by_id("key")  #获取输入框
input.send_keys("图书")  #搜索框输入图书

#或者另一种获取方式,需导入By包
#from selenium.webdriver.common.by import By
#driver.find_element(By.ID,"key")

Locate the search button through xpath, click search

#通过xpath获取搜索按钮元素并点击
btn = driver.find_element_by_xpath('//*[@id="search"]/div/div[2]/button')
btn.click() #点击
#driver.find_element(By.XPATH,'//*[@id="search"]/div/div[2]/button').click()

4. Back, Forward and Close

# 后退
driver.back()
# 前进
driver.forward()
# 关闭浏览器
driver.quit()

Guess you like

Origin blog.csdn.net/MrChenLen/article/details/120035810