Python3模擬登錄豆瓣(以豆瓣爲例)

首先,先哭一會兒.
因爲,這個模擬登錄我弄了很久,我是屬於沒經驗的那種.所以要弄很久.


登錄的目標站點是:
www.douban.com
豆瓣網站!






先上思路吧!
"""
技術要求:
Python第三方庫:
requests
json
"""
思路:
#這是最基本的防止反爬蟲的策略了!就是設置User-Agent和Referer!
headers = {"User-Agent":"Mozilla/5.0 (Windows NT 6.1; W…) Gecko/20100101 Firefox/59.0",
"Referer":"https://www.douban.com/account…w.douban.com/people/153954087/"}
#第二,設置data!
#因爲登錄一般來說都是POST請求,那麼就會涉及到表單的提交!
def login(CaptchaToken):
data = {"captcha-id":CaptchaToken,
"captcha-solution":input("請輸入驗證碼:"),
"form_email":"你自己的賬號",
"form_password":"你自己的密碼",
"login":u"登錄",
"redir":"https://www.douban.com/people/153954087/",
"source":"None"
}
#啥?什麼是POST?
#這個東西你百度的話還真的難懂,不如去試煉一番.
#怎麼試煉?
吶:https://v.qq.com/x/page/p0525lpt4x0.html


#提交表單的數據是通過POST,還是不懂POST的話,那麼請看"吶"的鏈接即可!
response = requests.post("https://accounts.douban.com/login",data,headers)
print(response.url)
return response.text


#最後一部分的就是關於豆瓣的驗證碼的問題了!
#所以這塊也不會是晦澀難懂,基本思路就是!
#獲取驗證碼圖片的URL,然後,url是不變的,變化的是url的id!
#驗證碼:
def CaptchaCode(url):
response = requests.get(url)
result = response.json()
CaptchaUrl = result["url"]
CaptchaToken = result["token"]
CodeImg = requests.get("https:"+CaptchaUrl,headers).content
f = open("douban_code.png","wb")
f.write(CodeImg)
f.close()


return CaptchaToken




完整代碼:


import requests




"""
思路:
1.設置headers,防止反扒
2.設置data
3.驗證碼的設置


"""


headers = {"User-Agent":"Mozilla/5.0 (Windows NT 6.1; W…) Gecko/20100101 Firefox/59.0",
"Referer":"https://www.douban.com/account…w.douban.com/people/153954087/"}
#驗證碼:
def CaptchaCode(url):
response = requests.get(url)
result = response.json()#轉化爲json格式的字符串!
CaptchaUrl = result["url"]
CaptchaToken = result["token"]
CodeImg = requests.get("https:"+CaptchaUrl,headers).content
f = open("douban_code.png","wb")
f.write(CodeImg)
f.close()


return CaptchaToken
#返回驗證碼的ID


#登錄
def login(CaptchaToken):
data = {"captcha-id":CaptchaToken,
"captcha-solution":input("請輸入驗證碼:"),
"form_email":"xxxxx",
"form_password":"xxxxxx",
"login":u"登錄",
"redir":"https://www.douban.com/people/153954087/",
"source":"None"
}


response = requests.post("https://accounts.douban.com/login",data,headers)
print(response.url)
return response.text






CaptchaToken = CaptchaCode("https://www.douban.com/j/misc/captcha")


response = login(CaptchaToken)
if "iven" in response:
print("登錄成功!")
else:
print("登錄失敗!")


print(response)
最後說一點,模擬登陸的意思就是 把你的爬蟲儘可能的模仿成瀏覽器的樣子去訪問目標站點!
這個就需要經驗和時間的累積了.
我總結了一點,關於懂和不懂的區別.
懂了不一定會,你懂了其思路,說是懂了.但是真正去實現的時候就會是一臉懵逼的!
所以,在學習這個東西時,做一下記錄.保持學習進程.
就這麼多!
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章