您好,登录后才能下订单哦!
小编给大家分享一下selenium+python如何实现自动化登录的方法,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!
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的最新版本,都会报错)
#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的方法,但是我使用的时候出现找不到情况,怀疑是浏览器版本不匹配的原因。
以上是“selenium+python如何实现自动化登录的方法”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。