Selenium Python 提供了一个简单的API 便于我们使用 Selenium WebDriver编写 功能/验收测试。 通过Selenium Python的API,你可以直观地使用所有的 Selenium WebDriver 功能 。Selenium Python提供了一个很方便的接口来驱动 Selenium WebDriver , 例如Firefox、Chrome、Ie,以及Remote,目前支持的python版本有2.7或3.2以上.
selenium 可以自动化测试、抢票、爬虫等工作。初次了解,现在模拟登录百度——即自动打开浏览器、自动输入账号密码并提交进行登录。
工作需要实现一个微博自动登录的操作,在网上差了一些资料,决定使用selenium+python实现
selenium 是一个web的自动化测试工具,主流一般配合java或者python使用,我这里使用的是python,可支持的浏览器基本包括所有主流浏览器IE、Mozilla Firefox、Google Chrome。
安装过程不再赘述,但是后续使用时,发现很多报错与版本兼容性有关,因此这里列出可用的版本搭配:
python2.7
selenium3.0.2
火狐驱动geckodriver.exe 版本v0.14.0 (使用高版本会出现异常报错)
火狐浏览器52.0.2 (32 位) (版本太低或53的最新版本,都会报错)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
|
#encoding=utf-8
from selenium import webdriver
import time
import os
#模拟登陆weibo
def getCookies(weibo):
""" 获取Cookies """
cookies = []
driver = webdriver.Firefox()
time.sleep( 3 ) #sleep一下,否则有可能报错
driver.get( "https://weibo.com/login/" )
#cur_path=os.getcwd()
#fileSuc = open(cur_path+"/login.html", 'w')
#fileSuc.write(driver.page_source)
#用户名 密码
elem_user = driver.find_element_by_xpath( '//input[@id="loginname"]' )
elem_user.send_keys( '*****@163.com' ) #浏览器版本不匹配的时候这里可能报错
elem_pwd = driver.find_element_by_xpath( '//input[@type="password"]' )
elem_pwd.send_keys( '*****' )
commit = driver.find_element_by_xpath( '//a[@node-type="submitBtn"]' )
commit.click()
time.sleep( 3 )
#fileSuc1 = open(cur_path+"/weibo2.html", 'w')
#fileSuc1.write(driver.page_source)
#print driver.title
#登录成功后获取cookie
cookie = {}
if "微博-随时随地发现新鲜事" in driver.title:
for elem in driver.get_cookies():
cookie[elem[ "name" ]] = elem[ "value" ]
if len (cookie) > 0 :
logger.warning( "Get Cookie Successful: %s" % account)
cookies.append(cookie)
continue
else :
logger.warning( "Get Cookie Failed: %s!" % account)
driver.close()
driver.quit()
return cookies
cookies = getCookies(myWeiBo)
print cookies
logger.warning( "Get Cookies Finish!( Num:%d)" % len (cookies))
|
find_element_by_xpath用来定位控件的位置,定位不到的时候,可以把网页的代码保存下来看看是否有对应的控件,如果是安全控件或者登录在js里实现,这种方法是获取不到的。
另外还有find_element_by_name、find_element_by_id的方法,但是我使用的时候出现找不到情况,怀疑是浏览器版本不匹配的原因。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://www.cnblogs.com/taurusfy/p/7007014.html