我一直试图使用我的凭据登录此网站,以便使用谷歌应用程序脚本获取我的个人资料名称。状态代码是200,我可以看到脚本能够获得cookie。但是,我得到的结果是Undefined
,而不是配置文件名称。
这就是我的尝试:
function loginAndParseProfile() {
var link = 'https://stackoverflow.com/users/login?ssrc=head&returnurl=https%3a%2f%2fstackoverflow.com%2f';
var options = {
"method": "get",
"headers": {
"User-Agent": "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36"
}
};
var res = UrlFetchApp.fetch(link, options);
var $ = Cheerio.load(res.getContentText());
var fkey = $("input[name='fkey']").first().attr('value');
var payload = {
'fkey': fkey,
'ssrc': 'head',
'email': 'emailaddress',
'password': 'password',
'oauth_version': '',
'oauth_server': ''
};
var options = {
"method" : "post",
'payload': payload,
'muteHttpExceptions': true,
"headers": {
"Content-Type": "application/x-www-form-urlencoded",
"User-Agent": "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36",
}
};
var loginURL = "https://stackoverflow.com/users/login?ssrc=head&returnurl=https%3a%2f%2fstackoverflow.com%2f";
var resp = UrlFetchApp.fetch(loginURL,options);
console.log(resp.getResponseCode());
console.log(resp.getAllHeaders()['Set-Cookie']);
var $ = Cheerio.load(resp.getContentText());
var item = $('a.my-profile > [class^="gravatar-wrapper"]').first().attr('title');
console.log(item);
}
如何使脚本工作?
-
通过将
followRedirects
设置为false
:禁用重定向var options = { "method" : "post", 'payload': payload, 'muteHttpExceptions': true, "headers": { "Content-Type": "application/x-www-form-urlencoded", "User-Agent": "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36", }, 'followRedirects': false };
-
从对
POST /users/login
请求的响应中获取acct
cookie:const acct = resp.getAllHeaders()['Set-Cookie'] .find(cookie => cookie.includes('acct=t=')) .match(/(acct=t=.*?)s/)[1];
-
提出
GET /
请求,提供acct
cookie,并获取您的配置文件名称:const profileRequest = UrlFetchApp.fetch('https://stackoverflow.com', { method: 'get', headers: { Cookie: acct } }); const $main = Cheerio.load(profileRequest.getContentText()); const myName = $main('.s-topbar--item.s-user-card > span').text(); console.log(myName);
如果凭据正确,则应输出robots.txt
。