Python+Selenium

安装步骤

  1. 安装 selenium
    Win:pip install selenium
    Mac:pip3 install selenium

from selenium import webdriver

browser = webdriver.Chrome()
browser.get(‘http://www.baidu.com/’)

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys

chrome_options = webdriver.ChromeOptions()

使用 headless 无界面浏览器模式

chrome_options.add_argument(‘–headless’) // 增加无界面选项
chrome_options.add_argument(‘–disable-gpu’) // 如果不加这个选项,有时定位会出现问题

启动浏览器,获取网页源代码

browser = webdriver.Chrome(chrome_options=chrome_options)
mainUrl = “https://www.taobao.com/
browser.get(mainUrl)
print(f"browser text = {browser.page_source}")
browser.quit()

元素定位

对象的定位应该是自动化测试的核心,要想操作一个对象,首先应该识别这个对象。一个对象就是一个人一样,他会有各种的特征(属性),如比我们可以通过一个人的身份证号,姓名,或者他住在哪个街道、楼层、门牌找到这个人。那么一个对象也有类似的属性,我们可以通过这个属性找到这对象。

webdriver 提供了一系列的对象定位方法,常用的有以下几种:

  • id 定位:find_element_by_id()

  • name 定位:find_element_by_name()

  • class 定位:find_element_by_class_name()

  • link 定位:find_element_by_link_text()

  • partial link 定位:find_element_by_partial_link_text()

  • tag 定位:find_element_by_tag_name()

  • xpath 定位:find_element_by_xpath()

  • css 定位:find_element_by_css_selector()