Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

无法获取Cookie,执行报错 #10

Open
z-meng-yu opened this issue May 16, 2024 · 1 comment
Open

无法获取Cookie,执行报错 #10

z-meng-yu opened this issue May 16, 2024 · 1 comment

Comments

@z-meng-yu
Copy link

WX20240516-104513@2x

@ljpkok
Copy link
Contributor

ljpkok commented May 20, 2024

我遇到了和你类似的问题,我注意到JD在登录后会自动跳转到其他页面,而不是返回主页,导致原有的代码失效。如果你也遇到了同样的情况,可以考虑使用以下的 main 函数替换原有的 main 函数,这对我来说在大部分时间是有效的,如果还是无法自动跳转到主页,可以手动跳转到主页来获取Cookie:

async def main():
    """使用pyppeteer库来登录京东、并获取cookie
    """
    browser = await launch(headless=False, dumpio=True, autoClose=False,
                           args=['--no-sandbox', '--window-size=1000,800', '--disable-infobars'])   # 进入有头模式
    context = await browser.createIncognitoBrowserContext() # 隐身模式

    # 关闭默认打开的第一个标签页
    pages = await browser.pages()
    if pages:
        await pages[0].close()

    page = await context.newPage()           # 打开新的标签页
    await page.setViewport({'width': 1000, 'height': 800})      # 页面大小一致
    await page.goto('https://home.m.jd.com/myJd/home.action',{'timeout': 1000*60}) # 访问主页、增加超时解决Navigation Timeout Exceeded: 30000 ms exceeded报错


    # 等待页面加载完成
    await page.waitForNavigation({'waitUntil': 'domcontentloaded'})

    # 检查页面是否跳转到登录页面
    if 'plogin.m.jd.com' in page.url:
        print("Redirected to login page. Logging in...")

        # 等待页面加载完成
        await page.waitForNavigation({'waitUntil': 'domcontentloaded'})

    await page.goto('https://home.m.jd.com/myJd/newhome.action', {'timeout': 1000 * 60})

    try:
        await page.waitFor(1000)
        elm = await page.waitForXPath('//*[@id="myHeader"]', timeout=0)
        if elm:
            cookie = await page.cookies()
            cookies_temp = []
            for i in cookie:
                cookies_temp.append('{}={}'.format(i["name"], i["value"]))
            cookies = '; '.join(cookies_temp)
            find_cookie(cookies)
    except Exception as e:
        print(f"Error during cookie retrieval: {e}")
        return False, f"Error during cookie retrieval: {str(e)}"
    finally:
        await browser.close()  # 确保无论如何都关闭浏览器

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants