如何使用pythonrequests登录google来检索登录页面的html?

2024-04-27 00:56:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试创建一个Python脚本,其中给定usernamepassword,脚本登录到Google,然后在登录时获取页面(例如Google主页)的HTML数据。你知道吗

我的代码不工作,但我不知道为什么。你知道吗

import sys
reload(sys)
sys.setdefaultencoding('utf-8')    # need to do this to be able to write html data to a file

from requests import session

payload = {
    'Email': EMAIL,
    'Passwd': PASSWORD
}

headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}    # to make Google think that this is a real browser not a python script

with session() as c:

    res1 = c.post('https://accounts.google.com/signin/challenge/sl/password', data=payload, headers=headers)

    res2 = c.get('http://www.google.com/', headers=headers)
    html = res2.text

    f = open("test.html", "w")
    f.write(html)
    f.close()

当我进入我编写的html文件时,它不会显示我已登录,因为有一个“登录”按钮。你知道吗

我打印出cookies,如果我不使用User-Agent头,当gethttp://google.com/时,会有一个“NID”cookie,当我使用User-Agent头时,会有一个GAPScookie。你知道吗

我从登录页面的html格式获得了EmailPasswd。你知道吗

有人知道怎么解决这个问题吗?你知道吗


Tags: toimport脚本comhtmlgooglesyspassword