selenium+python實現自動化登錄


工作需要實現一個微博自動登錄的操作,在網上差了一些資料,決定使用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 #encoding=utf-8
 2 from selenium import webdriver  
 3 import time  
 4 import os
 5 
 6 #模擬登陸weibo  
 7 
 8 def getCookies(weibo):
 9     """ 獲取Cookies """
10     cookies = []
11     driver = webdriver.Firefox()
12     time.sleep(3)   #sleep一下,否則有可能報錯
13     driver.get("https://weibo.com/login/")
14     #cur_path=os.getcwd()
15     #fileSuc = open(cur_path+"/login.html", 'w')
16     #fileSuc.write(driver.page_source)
17     #用戶名 密碼  
18     elem_user = driver.find_element_by_xpath('//input[@id="loginname"]') 
19     elem_user.send_keys('*****@163.com') #瀏覽器版本不匹配的時候這里可能報錯
20     elem_pwd = driver.find_element_by_xpath('//input[@type="password"]')
21     elem_pwd.send_keys('*****')
22     
23     commit = driver.find_element_by_xpath('//a[@node-type="submitBtn"]')
24     commit.click()
25     time.sleep(3)
26     #fileSuc1 = open(cur_path+"/weibo2.html", 'w')
27     #fileSuc1.write(driver.page_source)
28     #print driver.title  
29     #登錄成功后獲取cookie
30     cookie = {}
31     if "微博-隨時隨地發現新鮮事" in driver.title:
32         for elem in driver.get_cookies():
33             cookie[elem["name"]] = elem["value"]
34         if len(cookie) > 0:
35             logger.warning("Get Cookie Successful: %s" % account)
36             cookies.append(cookie)
37             continue
38     else:
39         logger.warning("Get Cookie Failed: %s!" % account)
40     
41     driver.close()  
42     driver.quit()  
43     return cookies
44 
45 cookies = getCookies(myWeiBo)
46 print cookies
47 logger.warning("Get Cookies Finish!( Num:%d)" % len(cookies))
find_element_by_xpath用來定位控件的位置,定位不到的時候,可以把網頁的代碼保存下來看看是否有對應的控件,如果是安全控件或者登錄在js里實現,這種方法是獲取不到的。
另外還有find_element_by_name、find_element_by_id的方法,但是我使用的時候出現找不到情況,懷疑是瀏覽器版本不匹配的原因。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM