关于用python写的登陆程序,怎么获取cookie值并返回出来
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了关于用python写的登陆程序,怎么获取cookie值并返回出来相关的知识,希望对你有一定的参考价值。
参考技术A 两种方式:一、
接口,可以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
Python爬虫 —— 知乎之selenium模拟登陆+requests.Session()获取cookies
代码如下:
1 # coding:utf-8 2 from selenium import webdriver 3 import requests 4 import sys 5 import time 6 from lxml import etree 7 # reload(sys) 8 # sys.setdefaultencoding(‘utf-8‘) 9 10 class Zhihu: 11 def __init__(self,homeurl): 12 self.homeurl = homeurl 13 14 def GetCookies(self): 15 browser = webdriver.Chrome() 16 browser.get("https://www.zhihu.com/signin") 17 browser.find_element_by_css_selector(".SignFlow-accountInput.Input-wrapper input").send_keys("13060882373") 18 browser.find_element_by_css_selector(".SignFlow-password input").send_keys("XXXXXX") 19 browser.find_element_by_css_selector(".Button.SignFlow-submitButton").click() 20 time.sleep(3) 21 # js = "window.scrollTo(0, document.body.scrollHeight);" 22 # browser.execute_script(js) 23 # time.sleep(3) 24 cookies = browser.get_cookies() 25 browser.quit() 26 return cookies 27 28 def Crawl(self): 29 s = requests.Session() 30 s.headers.clear() 31 for cookie in self.GetCookies(): 32 s.cookies.set(cookie[‘name‘], cookie[‘value‘]) 33 html = s.get(self.homeurl).text 34 html_tree = etree.HTML(html) 35 items = html_tree.xpath(‘//*[@id="root"]/div/main/div/div/div[1]/div[2]/div//div[@class="ContentItem AnswerItem"]/@data-zop‘) 36 for item in items: 37 # print item 38 content = eval(item) 39 authorName = content[‘authorName‘] 40 title = content[‘title‘] 41 print authorName + "回答了:" + title 42 43 44 zhihu = Zhihu(‘https://www.zhihu.com/‘) 45 zhihu.Crawl()
以上是关于关于用python写的登陆程序,怎么获取cookie值并返回出来的主要内容,如果未能解决你的问题,请参考以下文章
关于用python写的登陆程序,怎么获取cookie值并返回出来