模拟登录淘宝–Python
由于淘宝开始检测selenium,要绕过检测非常麻烦。故使用另外一款Python的自动化工具:Pyppeteer,来模拟登录淘宝获取cookie。目前没有遇到滑块验证(该有的还是会有的),放上粗超的demo代码,提供学习。
代码
# -*- 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%3A%2F%2Fwww.taobao.com%2F'
# 协程,开启个无限循环的程序流程,把一些函数注册到事件循环上。当满足事件发生的时候,调用相应的协程函数。
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有界面显示
代码简陋,只是提供学习参考,如有任何不当,请联系删除。谢谢!
更多分享文章,欢迎访问:downdawn
交流互动学习群,网罗分享学习资料。欢迎加入:861862805(如有打扰,请忽略。。)