Selenium+Python對開源中國官網進行模擬登陸

1.摘要:css

Selenium是一個開源的和便攜式的自動化軟件測試工具,用於測試Web應用程序有能力在不一樣的瀏覽器和操做系統運行。Selenium不是一個單一的工具,而是一套工具,幫助測試者更有效地基於Web的應用程序的自動化。html

咱們這裏用到的python

python:python3.6linux

操做系統:archlinuxgit

相關庫:github

timeweb

requestschrome

logging瀏覽器

2.Selenium和Python的安裝和配置cookie

Selenium相關文檔可參考

Selenium Python Bindings http://selenium-python.readthedocs.io/installation.html#introduction

Python相關文檔可參考python官網

https://www.python.org/

3.導入相關庫

import time
from selenium import webdriver
import requests
import logging

4.分析登陸頁面

(https://www.oschina.net/home/login?goto_page=https%3A%2F%2Fwww.oschina.net%2F)

發現咱們只須要關注三個地方,手機/郵箱這個輸入框,密碼框,登陸按鈕。利用chrome的檢查功能,檢查這三個地方得:

手機/郵箱   <input type="text" id="userMail" value="" placeholder="手機/郵箱" class="">

密碼框   <input type="password" id="userPassword" value="" placeholder="請輸入密碼">

登陸按鈕   <button type="button" class="btn btn-green block btn-login error">登陸</button>

5.編寫Selenium自動化登陸操做

username = browser.find_element_by_id("userMail")
username.clear()
username.send_keys(account)
psd = browser.find_element_by_id("userPassword")
psd.clear()
psd.send_keys(password)
commit = browser.find_element_by_tag_name("button")
commit.click()

關於Selenium的定位方法(根據名字就應該能猜出來吧,我就不作過多解釋了)

  • find_element_by_id
  • find_element_by_name
  • find_element_by_xpath
  • find_element_by_link_text
  • find_element_by_partial_link_text
  • find_element_by_tag_name
  • find_element_by_class_name
  • find_element_by_css_selector

6.獲取Cookie

 
for elem in browser.get_cookies():
    cookie+=elem["name"]+"="+ elem["value"]+"; "
if len(cookie) > 0:
    logger.warning("獲取cookie成功: %s" % account)
    cookies.append(cookie)
    continue

7.訪問問答頁面,判斷是否成功登陸

由於沒有登錄的話,沒法對某人進行提問且會進入登陸頁面,因此利用這個進行測試,是否成功登陸。。

headers={
'Accept':'*/*',
'Accept-Encoding':'gzip, deflate, br',
'Accept-Language':'zh-CN,zh;q=0.8',
    'Cookie':cookies[0],
    'User-Agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.96 Safari/537.36',
'hd-token':'hello',
'X-Requested-With':'XMLHttpRequest'
}
    req=requests.Session()
    t=req.get(url='https://www.oschina.net/question/ask?user=3392136',headers=headers)
碼雲https://git.oschina.net/nanxun/monidenglukaiyuanzhongguo.git
github https://github.com/nanxung/Selenium-Python-.git
相關文章
相關標籤/搜索