您的位置:首页 > 编程语言 > Python开发

python爬虫从入门到放弃(五)安装selenium并学习

2019-03-06 11:48 543 查看
版权声明:原创内容归汣净所有 https://blog.csdn.net/jiujing_/article/details/88206186

安装selenium

selenium 是一个web的自动化测试工具,其优点有

  • 免费,也不用再为破解QTP而大伤脑筋

  • 小巧,对于不同的语言它只是一个包而已,而QTP需要下载安装1个多G 的程序。

  • 这也是最重要的一点,不管你以前更熟悉C、 java、ruby、python、或都是C# ,你都可以通过selenium完成自动化测试,而QTP只支持VBS

  • 支持多平台:windows、linux、MAC ,支持多浏览器:ie、ff、safari、opera、chrome

  • 支持分布式测试用例的执行,可以把测试用例分布到不同的测试机器的执行,相当于分发机的功能。

安装前准备

电脑具备python,setuptools,pip
具体方法

安装selenium

1、通过pip 安装

PS C:\Users\datan> python -m pip install selenium

3、下载chromedriver.exe,前往https://sites.google.com/a/chromium.org/chromedriver/downloads根据自己电脑上的Chrome版本选择版本下载,

下载完成后解压到Chrome的安装目录,默认是在
C:\Program Files (x86)\Google\Chrome\Application

4、将谷歌浏览器的安装目录(默认是C:\Program Files (x86)\Google\Chrome\Application),添加到系统的用户环境变量path中

5、将以下测试代码复制并另存为selenium_test.py(文件存放的位置有自己决定,只是个临时测试文件)

from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.keys import Keys
import time

browser = webdriver.Chrome() # Get local session of Chrome
browser.get("http://www.yahoo.com") # Load page
assert "Yahoo" in browser.title
elem = browser.find_element_by_id("uh-search-box") # Find the query box
elem.send_keys("qq" + Keys.RETURN)
time.sleep(0.2) # Let the page load, will be added to the API

6、在文件存放的位置使用命令行运行: python selenium_test.py
如果有以下的错误信息:
1 AttributeError: ‘Service’ object has no attribute ‘process’

请检查步骤4、5是否正确配置了,如果确定无误请使用以下办法尝试解决:
将第四步解压出来的chromedriver.exe文件复制一份到当前测试文件的目录下,再执行测试文件。

跳出yahoo窗口则表示成功

使用selenium模拟登陆126邮箱。

Selenium+Handless Chrome

from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.keys import Keys
import time

driver = webdriver.Chrome()
driver.get("https://mail.126.com/")
time.sleep(2)

driver.switch_to.frame(driver.find_element_by_xpath("//iframe[starts-with(@id,'x-URS-iframe')]"))  # iframe是第一个大坑,必须切入才行,第二大坑是这个iframe的id是动态的,直接搞死初学者,解决办法是用starts-with
#提示来自 StalloneYang,链接https://blog.csdn.net/u011757108/article/details/88168215

time.sleep(1)
driver.find_element_by_xpath("//input[starts-with(@id,'auto-id-')]").clear()
time.sleep(1)
driver.find_element_by_xpath("//input[starts-with(@id,'auto-id-')]").send_keys("jzhou6")
time.sleep(1)
driver.find_element_by_xpath("//input[starts-with(@placeholder,'密码')]").clear()
time.sleep(1)
driver.find_element_by_xpath("//input[starts-with(@placeholder,'密码')]").send_keys("****")
time.sleep(1)
driver.find_element_by_xpath('//*[@id="dologin"]').click()
time.sleep(3)
driver.close()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: