python獲取cookie
A. 關於用python寫的登陸程序,怎麼獲取cookie值並返回出來
兩種方式:
一、
介面,可以pip install requests模塊,安裝一個requests,對介面支持簡單好用
例子,寫一個getcookie()方法
import requests
def getcookie():
data={'username':username,'password':pwd}
session=requests.session()
loginurl="http://xxx.com/login"
#具體要介面登錄後才可以獲得cookies
result=session.post(loginurl,data=data)
cookies=requests.utils.dict_from_cookiejar(session.cookies)
return cookies
二、
UI自動化登錄:可以easy_install -U selenium,安裝selenium模塊,支持UI自動化,模擬前端,用戶名、密碼登錄後,這種方式也可以獲得cookie
一個例子,登錄csdn,並且獲取cookie,用戶名和密碼我隱去了,可以參考。
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import selenium
import os,time
import sys
sys.path.append("..")
import web
import datetime
#默認得安裝一個火狐瀏覽器
class webconn:
def __init__(self,drivertype):
self.drivertype=drivertype
def web_conn(self):
PASS=0
FAIL=0
get_cookie={}
t=datetime.datetime.now()
starttime=datetime.datetime.now()
driver = webdriver.Firefox()
try:
driver.get('https://passport.csdn.net/account/login')
time.sleep(2)
assert u'帳號登錄' in driver.title
driver.find_element_by_id("username").send_keys(u"yoursername")
print "輸入用戶名"
driver.find_element_by_id("password").send_keys(u"yourpassword")
print "輸入密碼"
driver.find_element_by_class_name("logging").click()
time.sleep(2)
assert u'全球最大中文' in driver.title
driver.add_cookie({'name':'key-aaaaaa','value':'value-bbbb'})
for cookie in driver.get_cookies():
print "%s -> %s" %(cookie['name'],cookie['value'])
get_cookie[cookie['name'].encode("UTF-8")]=cookie['value'].encode("UTF-8")
print "cookie cookie cookie cookie cookie"
print get_cookie
PASS=PASS+1
except Exception,e:
print(str(Exception)+":"+str(e))
FAIL=FAIL+1
finally:
driver.close()
driver.quit()
endtime=datetime.datetime.now()
totaltime=endtime-starttime
usetime=str(endtime-starttime)
hour=usetime.split(':').pop(0)
minute=usetime.split(':').pop(1)
second=usetime.split(':').pop(2)
totaltime=float(hour)*60*60+float(minute)*60+float(second)
totaltime=str(totaltime)+"s"
return get_cookie
B. python爬蟲使用Cookie如何進行
Cookie,指某些網站為了辨別用戶身份、進行session跟蹤而儲存在用戶本地終端上的數據(通常經過加密),比如說有些網站需要登錄後才能訪問某個頁面,在登錄之前,你想抓取某個頁面內容是不允許的。那麼我們可以利用Urllib2庫保存我們登錄的Cookie,然後再抓取其他頁面就達到目的了,那麼python爬蟲使用Cookie如何進行?
C. 如何用python3 獲取cookie
使用requests這個庫吧
importrequests
url="http://www.google.com"
r=requests.get(url,timeout=5)
ifr.status_code==200:
forcookieinr.cookies:
print(cookie)#Use"printcookie"ifyouusePython2.
D. python獲取cookie後怎麼模擬登陸網站
運行平台:Windows
Python版本:Python3.x
IDE:Sublime text3
一、為什麼要使用Cookie
Cookie,指某些網站為了辨別用戶身份、進行session跟蹤而儲存在用戶本地終端上的數據(通常經過加密)。
比如說有些網站需要登錄後才能訪問某個頁面,在登錄之前,你想抓取某個頁面內容,登陸前與登陸後是不同的,或者不允許的。
使用Cookie和使用代理IP一樣,也需要創建一個自己的opener。在HTTP包中,提供了cookiejar模塊,用於提供對Cookie的支持。
三、總結
獲取成功!如果看過之前的筆記內容,我想這些代碼應該很好理解吧。
E. python讀取 cookies
ck = cookielib.MozillaCookieJar()
ck.load('#cookpath')
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(ck))
F. python 怎麼抓取firefox的cookie
firebug能獲取到的,python也一定能獲取,因為都是抓取http協議數據包。
方便的話貼下firebug抓取的cookie截圖,看能否幫到你。
G. python如何保存cookie到本地
python如何保存cookie到本地的方法:
第一次訪問頁面後,Server可將Cookie信息加入HTTP
Header返回給瀏覽器,瀏覽器會自動將這些信息保存在本地;
當再次訪問相同域名時,瀏覽器將對應Cookie信息隨請求一起發送,Server端可讀取這些信息進行處理。
Cookie可設置過期時間,到期後由瀏覽器自動刪除;
當我們要返回頁面時,首先輸出如下:
[python]
view
plain
print
"Content-type:
text/plain\n"
它其實是一個HTTP
Header,
連續碰到兩個換行表示HTTP
Header部分結束,剩餘部分將被做為數據處理;
包含了Cookie後輸出大致如下:
[python]
view
plain
print
"Content-Type:
text/html"
print
"Set-Cookie:
session=12345"
print
#
多加一個換行表示HTTP
Header部分結束
代碼:
setcookie.py
[python]
view
plain
#!/usr/bin/env
python
import
Cookie
import
datetime
import
random
expiration
=
datetime.datetime.now()
+
datetime.timedelta(days=30)
cookie
=
Cookie.SimpleCookie()
cookie["session"]
=
random.randint(0,1000000000)
cookie["session"]["domain"]
=
"localhost"
cookie["session"]["path"]
=
"/"
cookie["session"]["expires"]
=
\
expiration.strftime("%a,
%d-%b-%Y
%H:%M:%S
PST")
print
"Content-type:
text/plain"
print
cookie.output()
print
print
"Cookie
set
with:
"
+
cookie.output()
getcookie.py
[python]
view
plain
#!/usr/bin/env
python
import
Cookie
import
os
print
"Content-type:
text/plain\n"
try:
cookie
=
Cookie.SimpleCookie(os.environ["HTTP_COOKIE"])
print
"session
=
"
+
cookie["session"].value
except
(Cookie.CookieError,
KeyError):
print
"session
cookie
not
set!"
H. Python通過urllib.request獲取【伺服器返回】的cookie
F12是在瀏覽器里看的吧,兩個cookie應當一個是伺服器發給你的,讓你修改你本地的,另一個是你本地的,要發給伺服器的
一般都是python自己維護cookie,不用寫代碼去處理 除非想手動修改,我寫過的python自處理cookie的代碼
def__set_cookie(self):
"""
設置Cookie
:return:
"""
self.cj=http.cookiejar.MozillaCookieJar('Cookie.txt')
opener=urllib.request.build_opener(urllib.request.HTTPCookieProcessor(self.cj))
urllib.request.install_opener(opener)
I. 使用python怎麼獲取京東網站cookie進行登錄
# -*- coding: utf-8 -*-
# !/usr/bin/python
import os
import urllib2
import urllib
import cookielib
import re
import sys
from bs4 import BeautifulSoup
『『『
編碼方式的設置,在中文使用時用到中文時的處理方式
『『『
default_encoding = "utf-8"
if sys.getdefaultencoding() != default_encoding:
reload(sys)
sys.setdefaultencoding("utf-8")
def getHtml(url,data={}):
if(data=={}):
req=urllib2.Request(url)
else:
req=urllib2.Request(url,urllib.urlencode(data))
html=urllib2.urlopen(req).read()
return html
try:
cookie = cookielib.CookieJar()
cookieProc = urllib2.HTTPCookieProcessor(cookie)
except:
raise
else:
opener = urllib2.build_opener(cookieProc)
opener.addheaders = [(『User-Agent『,『Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11『)]
urllib2.install_opener(opener)
auth_url=『『
#auth_url = 『『
home_url=『『
#home_url = 『;
url = ""
login=getHtml(url)
#print login
loginSoup = BeautifulSoup(login,『html.parser『)
#查找登陸參數中的uuid
uuid = loginSoup.find_all("form")[0].find_all("input")[0][『value『]
print uuid
clrName=loginSoup.find_all("form")[0].find_all("input")[6][『name『]
clrValue=loginSoup.find_all("form")[0].find_all("input")[6][『value『]
『『『這倆參數不是必須。。。。
eid=loginSoup.find_all("form")[0].find_all("input")[4][『value『]
fp=loginSoup.find_all("form")[0].find_all("input")[5][『value『]
『『『
#下載驗證碼圖片:
checkPicUrl = loginSoup.find_all("div",id="o-authcode")[0].find_all("img")[0][『src2『]
req = getHtml(checkPicUrl)
checkPic = open("checkPic.jpg","w")
checkPic.write(req)
checkPic.close()
#調用mac系統的預覽(圖像查看器)來打開圖片文件
os.system(『open /Applications/Preview.app/ checkPic.jpg『)
checkCode = raw_input("請輸入彈出圖片中的驗證碼:")
#登錄URL
url = ""
# 登陸用戶名和密碼
postData = {
『loginname『:『你自己的賬號『,
『nloginpwd『:『你自己的密碼『,
『loginpwd『:『你自己的密碼『,
# 『machineNet『:『『,
# 『machineCpu『:『『,
# 『machineDisk『:『『,
str(clrName):str(clrValue),
『uuid『:uuid,
『authcode『: checkCode
}
passport=getHtml(url,postData)
print passport
# 初始化一個CookieJar來處理Cookie
『『『
cookieJar=cookielib.CookieJar()
# 實例化一個全局opener
opener=urllib2.build_opener(urllib2.HTTPCookieProcessor(cookieJar))
# 獲取cookie
req=urllib2.Request(auth_url,post_data,headers)
result = opener.open(req)
# 訪問主頁 自動帶著cookie信息
『『『
result = opener.open(『『)
# 顯示結果
#print result.read()
soup=BeautifulSoup(result,『html.parser『)
#昵稱
nickName = soup.find_all("input", id="nickName")[0]["value"]
print "nickName:",
print nickName
J. python 爬蟲為什麼要獲取響應的cookie
Cookie是指某些網站為了辨別用戶身份、進行session跟蹤而儲存在用戶本地終端上的數據(通常經過加密)。比如說有些網站需要登錄後才能訪問某個頁面,在登錄之前你想抓取某個頁面內容是不允許的。那麼可以利用Urllib庫保存登錄的Cookie,然後再抓取其他頁面,這樣就達到了你的目的。爬蟲過程中只用python來保存cookie信息模擬登錄是不行的,爬蟲限制有很多,例如同一IP短時間內多次訪問同一頁面,或者同一賬戶短時間內多次進行相同操作等等。