Selenium WebDriver 基于Python(一)

初始Selenium Web Driver

Selenium可以自动的操纵浏览器来做很多事情,它可以模拟我们与浏览器的交互,比如,访问网站,单击链接,填写表单,提交表单,浏览网页等,而且支持大多数主流的浏览器。如果要使用Selenium WebDriver,我们首先要选择一种语言来编写自动化脚本,而这个编程语言需要有Selenium client library支持。

我们使用支持Selenium client library的Python语言来编写自动化脚本。


本次将介绍基于Python的Selenium WebDriver client libray的安装步骤、基本特性和总体架构。

基于安装Python的Selenium包;

PyCharm - 选择和设置Python编辑器 ;

Selenium WebDriver 基于Python编写实例脚本。


安装Python

其中在Mac OS X系统上,Python是系统默认安装好的。

我的电脑Mac Pro的Python版本是2.7.11,在Python官网上 http://python.org/download/ 重新安装的最新版3.6.5。


安装Selenium包

Selenium安装包里包含了Selenium WebDriver Python client library。

下载途径:

1)使用pip安装工具: https://pip.pypa.io/en/latest/installing/

下载完成get-pip,然后打开终端,在其目录下执行python3 get-pip.py,

接着,执行 pip3 install -U selenium 来安装Selenium WebDriver client library(-U:将会更新已经安装的旧版本至新版本)。

2)Selenium网站

https://pypi.org/project/selenium/

python3 setuo.py install

http://selenium.googlecode.com/git/docs/api/py/api.html


PyCharm - 选择和设置Python编辑器

PyCharm是JetBrains公司出品的软件,有两个版本:社区版和专业版,社区版是免费的,专业版需要付费。

社区版能够很好的构建和运行Selenium脚本,并提供调试支持。

使用PyCharm时,第一次运行需要配置解释器。


Selenium基于Python的实例
# -*- coding:utf-8 -*-

# 需要从Selenium包中导入WebDriver才能使用Selenium WebDriver方法。
from selenium import webdriver

# 需要选用一个浏览器驱动实例,它会提供一个接口去调用Selenium命令来跟浏览器交互。
# create a new Firefox session
driver = webdriver.Firefox()
# 使用30秒隐式等待时间来定义Selenium执行步骤的超时时间
driver.implicitly_wait(30)
# 最大化浏览器窗口
driver.maximize_window()

# 调用driver.get()方法访问该应用程序,调用后WebDriver会等待,一直到页面加载完成才继续控制脚本。
# navigate to the application home page
driver.get('http://www.baidu.com/')

# 根据id/name/class_name进行搜索定位,成功后在清除
# get the search textbox
search_field = driver.find_element_by_id('kw')  # name:wd,class_name:s_ipt
search_field.clear()

# 进行搜索请求,并提交
# enter search keyword and submit
search_field.send_keys("路飞")
search_field.submit()

# get all the anchor elements which have product names displayed
# currently on result page using find_elements_by_xpath method
products = driver.find_elements_by_xpath("//h3[@class='t']/a")

# get the number of anchor elements found
print('Found' + str(products) + "products:")

# iterate through each anchor element and print the text that is
# name of the product
for product in products:
    print(product.text)

# close the browser window
driver.quit()

运行脚本,

发生错误:

解决方法:

https://github.com/mozilla/geckodriver/releases


下载适合的版本geckodriver,将文件移动到/usr/local/bin下即可。

最终执行结果为:

/XXX/TestPython.py
路飞的最新相关信息
路飞家族_百度百科
不败的路飞_百度百科
噩梦路飞_百度百科
海贼王903话路飞15亿成五皇仍最弱 尾田再次透露四皇实力排名|海贼...
关于路飞的50个秘密!路飞不为人知的一面_搜狐文化_搜狐网

Process finished with exit code 0

然后,Firefox关闭。


持续更新中。。。





猜你喜欢

转载自blog.csdn.net/duanmulirui/article/details/80749360
今日推荐