python模擬用戶瀏覽器登陸網站

【前置條件】

Python 2.7.13 |CentOS release 6.5

方案一:使用urllib2庫
首先使用自己的賬號和密碼在瀏覽器登錄,然後通過抓包拿到cookie,再將cookie放到請求之中發送請求即可,具體代碼如下:

# -*- coding: utf-8 -*-

import urllib2

# 構建一個已經登錄過的用戶的headers信息
headers = {
    "Host":"www.renren.com",
    "Connection":"keep-alive",
    "Upgrade-Insecure-Requests":"1",
    "User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36",
    "Accept":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
    "Accept-Language":"zh-CN,zh;q=0.8,en;q=0.6",
    # 添加抓包獲取的cookie,這個Cookie是保存了密碼無需重複登錄的用戶的Cookie,裏面記錄了用戶名及密碼等登錄信息(我這裏只顯示一部分)
    "Cookie": "anonymid=jpj3x8dl3bucfp; depovince=BJ; _r01_=1; jebe_key=03bdf34f-49ca-4aba-abff-d6552c90711e%7Ccfcd208495d565ef66e7dff9f98764da%7C1544494102650%7C0; jebecookies=1bca8ed4-b76b-4c5e-a599-ce7c2112f0cd|||||; JSESSIONID=abcZvYrHBc6em41wacBEw; ick_login=6c5bdd5d-b553-44be-a851-33b5130b4c69; _de=B5B94B4549137285E481BC4A8D8B28816DEBB8C2103DE356; p=783f97b6a51eea1dc5ee76b1e1a2a1702; first_login_flag=1; ln_uact=****; ln_hurl=http://hdn.xnimg.cn/photos/hdn421/20130628/1430/h_main_c7bN_86290000032f113e.jpg; t=395e99e55de1ae9abca18e8e05b612702; societyguester=395e99e55de1ae9abca18e8e05b612702; id=245451152; xnsid=64f44934; loginfrom=syshome"
}

# 通過headers裏的報頭信息(主要是Cookie信息),構建Request對象
request = urllib2.Request("http://www.renren.com/", headers = headers)
# 直接訪問renren主頁,服務器會根據headers報頭信息(主要是Cookie信息),判斷這是一個已經登錄的用戶,並返回相應的頁面
response = urllib2.urlopen(request)
# 打印響應內容
print response.read()
request = urllib2.Request("http://www.renren.com/226003000/profile?v=info_timeline", headers = headers)
response = urllib2.urlopen(request)
print response.read()

方案二:

linux沒有成功,windows實驗成功

# -*- coding: utf-8 -*-
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time

driver = webdriver.PhantomJS(executable_path=r'F:\tools\phantomjs-2.1.1-windows\bin\phantomjs.exe')
driver.get("http://www.renren.com/")

# 輸入賬號密碼
driver.find_element_by_name("email").send_keys("用戶名")
driver.find_element_by_name("password").send_keys("密碼")

# 模擬點擊登錄
driver.find_element_by_xpath("//input[@class='input-submit login-btn']").click()

# 等待3秒
time.sleep(3)

# 生成登陸後快照
driver.save_screenshot("renren.png")

【異常1】
Traceback (most recent call last):
  File "loginsp.py", line 2, in <module>
    from selenium import webdriver
ImportError: No module named selenium
解決方法:
F:\workspace\python>pip install selenium

【異常2】
    os.path.basename(self.path), self.start_error_message)
selenium.common.exceptions.WebDriverException: Message: 'phantomjs' executable n
eeds to be in PATH.
解決方法:
下載phantomjs.exe,解壓後在代碼中配置具體路徑:
http://phantomjs.org/download.html
 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章