❶ 怎樣用python設計一個爬蟲模擬登陸知乎
兩種方法:
1.帶cookielib和urllib2
import urllib2
import urllib
import cookielib
def login():
email = raw_input("請輸入用戶名:")
pwd = raw_input("請輸入密碼:") data={"email":email,"password":pwd}
post_data=urllib.urlencode(data) cj=cookielib.CookieJar()
opener=urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))headers
={"User-agent":"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1"}website =
raw_input('請輸入網址:')req=urllib2.Request(website,post_data,headers)content=opener.open(req)print
content.read()
2.使用selenium
import selenium import webdriver
browser=webdriver.Firefox()
browser.get("Url")
browser.find_element_by_id(" ").sendkey("username")
browser.find_element_by_id(" ").sendkey("pass")
browser.find_element_by_id(" ").click()
其實我這個最簡單了,用的python3,requests, 只需要驗證一次,就會保存cookies,下次登錄使用cookies登錄。
第一步、打開首頁獲取_xref值,驗證圖片 第二步、輸入賬號密碼 第三步、看是否需要驗證、要則下載驗證碼圖片,手動輸入
第四步、判斷是否登錄成功、登錄成功後獲取頁面值。
❷ 如何使用python語言實現用戶登錄系統
1、使用python3執行程序。按提示輸入1或2,登錄或退出程序
2、輸入用戶名後,如果用戶名被鎖定及無效用戶名,程序會退出,請確保輸入正確。
3、輸入用戶名正確後,輸入密碼。用戶名正確的情況下,密碼連續輸錯三次,用戶將被鎖定,禁止登錄系統
❸ python作業:1.設計賬號登錄程序,要求如下:(1)動態獲取用戶名和密碼,格式為"用戶名:密碼"
這個需求沒說清楚用什麼平台,比如是桌面版,還是web版。對所用技術或者庫有沒有什麼限制。
❹ Python設計一個用戶名和密碼
name=input()
if name=='這個地方是你判斷用的用戶名':
縮進pass=input()
縮進if pass=='這里是你判斷的密碼':
縮進縮進print('用戶名密碼都對')
縮進else:
縮進縮進print('密碼不對')
else:
縮進print('用戶名不對')
❺ python程序編寫登錄程序
count = 0
while count<3:
name = input('請輸入賬號:')
password = input('請輸入密碼:')
if not name or not password:
print('賬號密碼不能為空')
right_name = 'admin'
right_password = '123xyz'
if name == right_name:
if password == right_password:
print('歡迎{}登錄'.format(name))
break
else:
print('用戶名密碼錯誤')
else:
print('用戶名密碼錯誤')
count += 1
❻ Python怎麼通過字典的鍵和值做一個登錄程序
LZ,登陸功能有兩個子功能:注冊與登陸,,初學版如下:
dic={}
a=raw_input("Pleaseinputyourname...")
b=raw_input("Pleaseinputyourpasscode...")
dic[a]=b
printa,dic[a]
print'*******'
c=raw_input("Pleaseinputyourname...")
ifc==a:
d=raw_input("Pleaseinputyourpasscode...")
ifd==dic[a]:
print'Welcomeback%s'%c,'andyourpasscodeis%s',dic[a]
print'End...'
函數版如下:
#!/usr/bin/python
#-*-coding:utf-8-*-
importos
dic={}
deflogin(name,passcode):
dic['name']=name
dic['passcode']=passcode
defregister():
whileTrue:
n=raw_input("Pleaseinputyourname...")
ifn==dic['name']:
p=raw_input("Pleaseinputyourpasscode...")
ifp==dic['passcode']:
print'Welcomeback%s'%dic['name'],'andyourpasscodeis%s',dic['passcode']
print'End...'
break
else:
print'Yourpasscodeisnotcorrect,tryagain...'
continue
else:
print"Youdon'thaveanaccount,pleaseregister..."
break
a=raw_input("Pleaseinputyourname...")
b=raw_input("Pleaseinputyourpasscode...")
login(a,b)
print'**'
register()
字典的使用在面向對象的編程也是很靈活的,常用作可變長度參數傳遞;推薦一個網址:http://blog.csdn.net/moodytong/article/details/7647684
科科。。
❼ 請大家用Python幫忙設計用戶登錄程序。謝謝
可以搞100替你消災
❽ 使用python做登陸程序,在資料庫中查找用戶名和密碼是否正確
import MySQLdb
conn=MySQLdb.connect(user='root',passwd='pwd',host='127.0.0.1',db='python_test')
cur=conn.cursor()
cur.execute("select * from users where uid='101' and login='ong'")
##uid 是你的密碼 ;login是你的用戶名
num=0
for data in cur.fetchall():
num=num+1
print data
if(num != 0):
print '登陸成功'
else:
print '用戶名或密碼未找到'
cur.close()
conn.commit()
conn.close()
如果還有其他問題可以再問
❾ python簡單程序設計:許多計算機程序系統都需要登錄,且要求賬號密碼輸入錯誤不得超過三次
##注意:最左邊每個=表示一個空格
##修改成你的姓名
name="aabb"
c,userinfo=0,{"account":"123","password":"456","count":3}
t=input("請輸入賬號:")
while t!=userinfo["account"] and c<=userinfo["count"]:
====c=c+1
====t=input("賬號錯誤,請重新輸入:")
if c<=userinfo["count"]:
====t=input("請輸入密碼:")
====while t!=userinfo["password"] and c<=userinfo["count"]:
========t=input("密碼錯誤,請重新輸入:")
========c=c+1
if c<=userinfo["count"]:
====print("歡迎%s登錄到本系統!" %name)
else:
====print("你登錄次數過多。%s,請聯系管理員。" %name)
❿ 怎樣用Python設計一個爬蟲模擬登陸知乎
給你一個例子,可以看看:
import requests
import time
import json
import os
import re
import sys
import subprocess
from bs4 import BeautifulSoup as BS
class ZhiHuClient(object):
"""連接知乎的工具類,維護一個Session
2015.11.11
用法:
client = ZhiHuClient()
# 第一次使用時需要調用此方法登錄一次,生成cookie文件
# 以後可以跳過這一步
client.login("username", "password")
# 用這個session進行其他網路操作,詳見requests庫
session = client.getSession()
"""
# 網址參數是賬號類型
TYPE_PHONE_NUM = "phone_num"
TYPE_EMAIL = "email"
loginURL = r"http://www.hu.com/login/{0}"
homeURL = r"http://www.hu.com"
captchaURL = r"http://www.hu.com/captcha.gif"
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
"Accept-Encoding": "gzip, deflate",
"Host": "www.hu.com",
"Upgrade-Insecure-Requests": "1",
}
captchaFile = os.path.join(sys.path[0], "captcha.gif")
cookieFile = os.path.join(sys.path[0], "cookie")
def __init__(self):
os.chdir(sys.path[0]) # 設置腳本所在目錄為當前工作目錄
self.__session = requests.Session()
self.__session.headers = self.headers # 用self調用類變數是防止將來類改名
# 若已經有 cookie 則直接登錄
self.__cookie = self.__loadCookie()
if self.__cookie:
print("檢測到cookie文件,直接使用cookie登錄")
self.__session.cookies.update(self.__cookie)
soup = BS(self.open(r"http://www.hu.com/").text, "html.parser")
print("已登陸賬號: %s" % soup.find("span", class_="name").getText())
else:
print("沒有找到cookie文件,請調用login方法登錄一次!")
# 登錄
def login(self, username, password):
"""
驗證碼錯誤返回:
{'errcode': 1991829, 'r': 1, 'data': {'captcha': '請提交正確的驗證碼 :('}, 'msg': '請提交正確的驗證碼 :('}
登錄成功返回:
{'r': 0, 'msg': '登陸成功'}
"""
self.__username = username
self.__password = password
self.__loginURL = self.loginURL.format(self.__getUsernameType())
# 隨便開個網頁,獲取登陸所需的_xsrf
html = self.open(self.homeURL).text
soup = BS(html, "html.parser")
_xsrf = soup.find("input", {"name": "_xsrf"})["value"]
# 下載驗證碼圖片
while True:
captcha = self.open(self.captchaURL).content
with open(self.captchaFile, "wb") as output:
output.write(captcha)
# 人眼識別
print("=" * 50)
print("已打開驗證碼圖片,請識別!")
subprocess.call(self.captchaFile, shell=True)
captcha = input("請輸入驗證碼:")
os.remove(self.captchaFile)
# 發送POST請求
data = {
"_xsrf": _xsrf,
"password": self.__password,
"remember_me": "true",
self.__getUsernameType(): self.__username,
"captcha": captcha
}
res = self.__session.post(self.__loginURL, data=data)
print("=" * 50)
# print(res.text) # 輸出腳本信息,調試用
if res.json()["r"] == 0:
print("登錄成功")
self.__saveCookie()
break
else:
print("登錄失敗")
print("錯誤信息 --->", res.json()["msg"])
def __getUsernameType(self):
"""判斷用戶名類型
經測試,網頁的判斷規則是純數字為phone_num,其他為email
"""
if self.__username.isdigit():
return self.TYPE_PHONE_NUM
return self.TYPE_EMAIL
def __saveCookie(self):
"""cookies 序列化到文件
即把dict對象轉化成字元串保存
"""
with open(self.cookieFile, "w") as output:
cookies = self.__session.cookies.get_dict()
json.mp(cookies, output)
print("=" * 50)
print("已在同目錄下生成cookie文件:", self.cookieFile)
def __loadCookie(self):
"""讀取cookie文件,返回反序列化後的dict對象,沒有則返回None"""
if os.path.exists(self.cookieFile):
print("=" * 50)
with open(self.cookieFile, "r") as f:
cookie = json.load(f)
return cookie
return None
def open(self, url, delay=0, timeout=10):
"""打開網頁,返回Response對象"""
if delay:
time.sleep(delay)
return self.__session.get(url, timeout=timeout)
def getSession(self):
return self.__session
if __name__ == '__main__':
client = ZhiHuClient()
# 第一次使用時需要調用此方法登錄一次,生成cookie文件
# 以後可以跳過這一步
# client.login("username", "password")
# 用這個session進行其他網路操作,詳見requests庫
session = client.getSession()