欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Python之Selenium自动化浏览器测试详解

程序员文章站 2022-03-08 17:55:34
目录python之selenium(自动化浏览器测试)1.安装selenium2.下载对应版本的浏览器驱动3.测试code,打开一个网页,并获取网页的标题4.一个小样例总结python之seleniu...

python之selenium(自动化浏览器测试)

1.安装selenium

pip install selenium -i https://pypi.tuna.tsinghua.edu.cn/simple

2.下载对应版本的浏览器驱动

http://npm.taobao.org/mirrors/chromedriver/

Python之Selenium自动化浏览器测试详解

这是我的。

Python之Selenium自动化浏览器测试详解

把解压后的驱动放在自己的python.exe 目录下。

Python之Selenium自动化浏览器测试详解

3.测试code,打开一个网页,并获取网页的标题

from selenium.webdriver import chrome
if __name__ == '__main__':
    web = chrome()
    web.get("https://baidu.com")
    print(web.title)

Python之Selenium自动化浏览器测试详解

Python之Selenium自动化浏览器测试详解

4.一个小样例

from selenium.webdriver import chrome
if __name__ == '__main__':
    web = chrome()
    url = 'https://ac.nowcoder.com/acm/home'
    web.get(url)
	# 获取要点击的a标签
    el = web.find_element_by_xpath('/html/body/div/div[3]/div[1]/div[1]/div[1]/div/a')
	# 点击
    el.click()                          # "/html/body/div/div[3]/div[1]/div[2]/div[2]/div[2]/div[1]/h4/a"
    # 爬取想要的内容
    lists = web.find_elements_by_xpath("/html/body/div/div[3]/div[1]/div[2]/div[@class='platform-item js-item ']/div["
                                       "2]/div[1]/h4/a")
    print(len(lists))
    for i in lists:
        print(i.text)

Python之Selenium自动化浏览器测试详解

5.自动输入并跳转

from selenium.webdriver import chrome
from selenium.webdriver.common.keys import keys
import time
if __name__ == '__main__':
    web = chrome()
    url = 'https://ac.nowcoder.com/acm/home'
    web.get(url)
    el = web.find_element_by_xpath('/html/body/div/div[3]/div[1]/div[1]/div[1]/div/a')
    el.click()
    time.sleep(1)
    input_el = web.find_element_by_xpath('/html/body/div/div[3]/div[1]/div[1]/div[1]/form/input[1]')
    input_el.send_keys('牛客', keys.enter)
    #  do something

总结

本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注的更多内容!