如何使用Java代码登录网站?

Ys3

我想编写代码以使用Java登录网站。

这是代码:

package login;

import java.net.*;
import java.io.*;

public class ConnectToURL {

    // Variables to hold the URL object and its connection to that URL.
    private static URL URLObj;
    private static URLConnection connect;

    public static void main(String[] args) {
        try {
            CookieManager cManager = new CookieManager();
            CookieHandler.setDefault(cManager);
            // Establish a URL and open a connection to it. Set it to output mode.
            URLObj = new URL("https://accounts.google.com/ServiceLogin?service=mail&continue=https://mail.google.com/mail/#identifier");
            connect = URLObj.openConnection();
            connect.setDoOutput(true);  
        }
        catch (MalformedURLException ex) {
            System.out.println("The URL specified was unable to be parsed or uses an invalid protocol. Please try again.");
            System.exit(1); 
        }
        catch (Exception ex) {
            System.out.println("An exception occurred. " + ex.getMessage());
            System.exit(1);
        }

        try {
            // Create a buffered writer to the URLConnection's output stream and write our forms parameters.
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(connect.getOutputStream()));
            writer.write("[email protected]&Passwd=123456&submit=Login");
            writer.close();

            // Now establish a buffered reader to read the URLConnection's input stream.
            BufferedReader reader = new BufferedReader(new InputStreamReader(connect.getInputStream()));

            String lineRead = "";

            // Read all available lines of data from the URL and print them to screen.
            while ((lineRead = reader.readLine()) != null) {
                System.out.println(lineRead);
            }

            reader.close();
        }
        catch (Exception ex) {
            System.out.println("There was an error reading or writing to the URL: " + ex.getMessage());
        }
    }
}

我已经在Facebook和Gmail上尝试过此代码,但问题是它没有用。

它一直告诉我未启用cookie。(我使用了chrome浏览器,并且已启用它们)。

还有其他方法可以做到这一点吗?

catch23

如果您的目标只是登录某个网站,那么更好的解决方案是使用Selenium Web Driver

它具有用于创建现代驱动程序实例并与其Web元素一起运行的API。

代码示例

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;

public class Example  {

    public static void main(String[] args) {
        // Create a new instance of the html unit driver
        // Notice that the remainder of the code relies on the interface, 
        // not the implementation.
        WebDriver driver = new HtmlUnitDriver();

        // And now use this to visit Google
        driver.get("http://www.google.com");

        // Find the text input element by its name
        WebElement element = driver.findElement(By.name("q"));

        // Enter something to search for
        element.sendKeys("Cheese!");

        // Now submit the form. WebDriver will find the form for us from the element
        element.submit();

        // Check the title of the page
        System.out.println("Page title is: " + driver.getTitle());

        driver.quit();
    }
}

它还具有如何管理cookie的解决方案-Cookies

只需查看文档,了解如何配置驱动程序实例和管理Web元素,首选方法是使用Page Object pattern

更新:

为了从没有id没有name属性的网页上获取位置,可以使用xpath表达式来完成,为此,非常有用的是firefox扩展,例如:

并使用简洁的Xpath函数

例如:

<table>
    <tr>
        <td>
            <p>some text here 1</p>
        </td>
    </tr>
    <tr>
        <td>
            <p>some text here 2</p>
        </td>
    </tr>
    <tr>
        <td>
            <p>some text here 3</p>
        </td>
    </tr>
</table>

为了获取文本,some text here 2您可以使用以下xpath:

// tr [2] / td / p

如果您知道文本是静态的,则可以使用contains()

// p [包含(text(),'这里有些文本2')]

要检查此页面上的xpath是否唯一,最好使用控制台。
这里介绍了操作方法如何验证XPath表达式

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章