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短时间内多次访问同一页面,或者同一账户短时间内多次进行相同操作等等。