PhantomJS - Login to Twitch Through jQuery

2019-09-18 02:06发布

问题:

I am looking for a way to login to twitch through PhantomJS. The code I have now is not working when I look through "e.png"

var page = require('webpage').create();

page.open('http://www.twitch.tv/login', function() {
    page.includeJs("http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js", function() {
        page.evaluate(function() {
            $("login_user_login").val("username");
            $("user[password]").val("password");
            $("button").click(); // click login button
            page.render("e.png"); // see if anything happens
        });
        phantom.exit();
    });
});

I have found a link on how to do it through selenium here: Selenium Twitch

HTML (For selectors, per request): https://jsfiddle.net/r8szj7wy/1/

<input class="field text med-long" id="login_user_login" name="user[login]" tabindex="8" type="text" />

<input class="field text med-long" id="user[password]" name="user[password]" tabindex="9" type="password" value="" />

<button class="button primary" tabindex="11" type="submit">Log In

回答1:

Impossible render

page.evaluate() is the sandboxed page context. It doesn't have access to page or any other variables defined outside of it. You need to move the page.render("e.png") outside and behind it to see anything.

ID selectors

Your selectors are wrong. login_user_login and user[password] are supposed to be ids, but you're writing the CSS selector as if there are login_user_login and user elements in the DOM which is not the case. Correct ID selectors would be #login_user_login and [id='user[password]']. Note that the second one must be written differently than the first one, because it contains [] which is reserved for attribute selectors.

Page load waiting

And finally, after you click to login, it takes a while, so you need to wait until the page has reloaded. You can use a static timeout using setTimeout or a more sophisticated method using waitFor from the examples.

Final simple script:

var page = require('webpage').create();

page.open('http://www.twitch.tv/login', function() {
    page.includeJs("http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js", function() {
        page.evaluate(function() {
            $("#login_user_login").val("username");
            $("[id='user[password]']").val("password");
            $(".button.primary:first").click(); // click login button
        });
        setTimeout(function(){
            page.render("e.png"); // see if anything happens
            phantom.exit();
        }, 5000); // 5 seconds
    });
});