模擬登陸淘寶


目錄[-]

淘寶--模擬登錄

使用pyppeteer模擬登錄淘寶,獲取cookie。

代碼

# -*- coding: utf-8 -*- import asyncio from pyppeteer import launch import time from retry import retry # 設置重試次數用的 count = 1 async def main(username, password, url): # 主函數 browser = await launch({'headless': True, 'args': ["--disable-infobars"]}) # headless設置無界面模式 page = await browser.newPage() await page.goto(url) print('注入js') # 以下為插入中間js,將淘寶會為了檢測瀏覽器而調用的js修改其結果。 await page.evaluate('''() =>{ Object.defineProperties(navigator,{ webdriver:{ get: () => undefined } }) }''') try: await page.click('a.forget-pwd.J_Quick2Static') print('切換到密碼登錄頁面') cookie = await login(page, username, password) return cookie except Exception as e: print('直接進入密碼登錄頁面', e) cookie = await login(page, username, password) return cookie async def login(page, username, password): # 登錄動作 time.sleep(1) print('輸入賬號和密碼') await page.type('input#TPL_username_1', username) time.sleep(1) await page.type('input#TPL_password_1', password) time.sleep(1) # 點擊搜索按鈕 await page.click('button#J_SubmitStatic') time.sleep(2) print('點擊登錄') # 在while循環里強行查詢某元素進行等待 # while not await page.waitForXPath('//li[@id="J_SiteNavLogin"]'): # return None print('登錄成功!') ck = await get_cookie(page) await save_cookie(ck) return ck async def get_cookie(page): # 獲取登錄后cookie cookies_list = await page.cookies() cookies = '' for cookie in cookies_list: str_cookie = '{0}={1};' str_cookie = str_cookie.format(cookie.get('name'), cookie.get('value')) cookies += str_cookie print(cookies) return cookies async def save_cookie(cookies): # 保存到本地 with open(r'./cookies.txt', 'w', encoding='utf-8') as f: f.write(cookies) print('保存成功') @retry(tries=3) def run(): global count print('第%s次嘗試請求' % count) username = '' # 輸入你的賬號 password = '' # 輸入你的密碼 url = 'https://login.taobao.com/member/login.jhtml?redirectURL=https://www.taobao.com/' # 協程,開啟個無限循環的程序流程,把一些函數注冊到事件循環上。當滿足事件發生的時候,調用相應的協程函數。 loop = asyncio.get_event_loop() m = main(username, password, url) ck = loop.run_until_complete(m) # 將協程注冊到事件循環,並啟動事件循環 count += 1 return ck def tb_cookies(): ck = run() if ck is not None: return ck if __name__ == '__main__': tb_cookies()

使用說明

在username和password處輸入你的賬號和密碼

launch的headless默認設置為True是無界面模式,調試可以改為False有界面顯示

來自:http://www.downdawn.com/blog/detail/9/


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM