如果陈述没有错误,我如何制作get方法

时间:2019-01-28 03:33:50

标签: java phantomjs

我想在从该类继承的其他类中使用ids值

if (title.equals("***")) {
                String ids = driver.findElement(By.name("Idsession")).getAttribute("value");
            }

我试图创建一个get方法,因此代码将是

 if (title.equals("***")) {
                String ids = driver.findElement(By.name("Idsession")).getAttribute("value");
public String getID() {
                        return ids;
                    }
                }

但是我遇到错误

  

线程“ AWT-EventQueue-0”中的异常java.lang.Error:尚未解决   编译问题:令牌上的语法错误,放错位置   语法错误,插入“;”完成声明

     

在Login.initialize(Login.java:275)时登录(Login.java:108)     在Login $ 1.run(Login.java:91)处   java.awt.event.InvocationEvent.dispatch(来源未知)   java.awt.EventQueue.dispatchEventImpl(未知源)在   java.awt.EventQueue.access $ 500(未知源)   java.awt.EventQueue $ 3.run(未知源)   java.awt.EventQueue $ 3.run(未知源)   java.security.AccessController.doPrivileged(本机方法),位于   java.security.ProtectionDomain $ JavaSecurityAccessImpl.doIntersectionPrivilege(未知   源)位于java.awt.EventQueue.dispatchEvent(未知源)位于   java.awt.EventDispatchThread.pumpOneEventForFilters(未知来源)     在java.awt.EventDispatchThread.pumpEventsForFilter(未知来源)     在java.awt.EventDispatchThread.pumpEventsForHierarchy(未知   源)位于java.awt.EventDispatchThread.pumpEvents(未知源)     在java.awt.EventDispatchThread.pumpEvents(未知来源)   java.awt.EventDispatchThread.run(未知来源)

完整代码

import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.TimeUnit;
//import javax.swing.border.EmptyBorder;

import javax.imageio.ImageIO;
/*
import java.io.IOException;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
*/
import org.openqa.selenium.phantomjs.PhantomJSDriver;

import javax.swing.ImageIcon;
import javax.swing.JButton;
//import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
//import javax.swing.plaf.metal.MetalBorders.TextFieldBorder;

import org.openqa.selenium.By;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
//import java.awt.Point;
//import org.openqa.selenium.firefox.FirefoxDriver;
import org.apache.commons.io.FileUtils;
import org.omg.CORBA.portable.InputStream;
//import org.apache.log4j.PropertyConfigurator;
import org.openqa.selenium.OutputType;

import org.openqa.selenium.TakesScreenshot;

import javax.swing.JPanel;
import javax.swing.JPasswordField;


//import java.io.File;
//import java.io.IOException;
//import java.util.concurrent.TimeUnit;
//import org.apache.commons.io.FileUtils;
//import org.openqa.selenium.OutputType;
//import org.openqa.selenium.TakesScreenshot;
//import org.openqa.selenium.chrome.ChromeDriver;



public class Login extends JFrame {
    private JFrame frame;
    private JTextField daten;
    private JLabel background;
    private JLabel cinlabel;
    private JLabel title_1;
    private JLabel datalabel;
    private JTextField code;
    private JLabel codelabel;
    private JPasswordField CIN;
    private JLabel lblVersionBeta;
    public WebDriver driver;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {

        try {
            // body of main method goes here, including any other error handling
          } catch (Throwable t) {
            JOptionPane.showMessageDialog(
                null, t.getClass().getSimpleName() + ": " + t.getMessage());
            throw t; // don't suppress Throwable
          }

        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    Login window = new Login();
                    //window.frame.setUndecorated(true);
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        });
        //PropertyConfigurator.configure("C:\\Users\\MJ\\eclipse-workspace\\FindMyResults\\src\\log4j.properties");
    }

    /**
     * Create the application.
     * @throws IOException 
     */
    public Login() throws IOException {
        initialize();

    }

    /**
     * Initialize the contents of the frame.
     * @throws IOException 
     */
    private void initialize() throws IOException {


        frame = new JFrame();
        //java.awt.Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        //int w=screenSize.width;
        //int h=screenSize.height;
        //if (w==1366 && h==768) {
            frame.setBounds(100, 100, 1015, 600);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.getContentPane().setLayout(null);
        //}else {
        //  frame.setBounds(100, 100, 1024, 768);
        //  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //  frame.getContentPane().setLayout(null);
        //}


        /*java.awt.Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        setBounds(0,0,screenSize.width, screenSize.height);
        setVisible(true);*/

        codelabel = new JLabel("Code de s\u00E9curit\u00E9 \t");
        codelabel.setFont(new Font("Dubai Medium", Font.PLAIN, 18));
        codelabel.setBounds(764, 279, 182, 14);
        frame.getContentPane().add(codelabel);

        cinlabel = new JLabel("CIN ou Identifiant DGCI ");
        cinlabel.setFont(new Font("Dubai Medium", Font.PLAIN, 18));
        cinlabel.setBounds(574, 74, 294, 14);
        frame.getContentPane().add(cinlabel);

        datalabel = new JLabel("Date de naissance (jj/mm/aaaa)\t");
        datalabel.setFont(new Font("Dubai Medium", Font.PLAIN, 18));
        datalabel.setBounds(574, 183, 294, 14);
        frame.getContentPane().add(datalabel);
        URL title =getClass().getResource("/images/title.png");

        CIN = new JPasswordField();
        CIN.setBounds(574, 99, 396, 50);
        frame.getContentPane().add(CIN);

        daten = new JTextField();
        daten.setBackground(new Color(248, 248, 255));
        daten.setBounds(574, 208, 396, 50);
        daten.setForeground(new Color(0, 0, 0));
        daten.setFont(new Font("Helvetica", Font.PLAIN, 18));
        daten.setColumns(10);
        frame.getContentPane().add(daten);




/*
        // Create a trust manager that does not validate certificate chains
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
            }

            public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
            }
        } };

        // Install the all-trusting trust manager
        try {
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        } catch (Exception e) {
        }

        try {
            editorPane.setPage(url);
            //editorPane.scrollToReference(reference);
        } catch (IOException e) {
            System.err.println("Attempted to read a bad URL: " + url);
        }

        */
        //URL browser =getClass().getResource("/browser/phantomjs.exe");
        System.setProperty("phantomjs.binary.path", "phantomjs.exe");
        WebDriver driver = new PhantomJSDriver();

        //driver.manage().Window.Size = new Size(1920, 1080);
        driver.get("https://www4.inscription.tn/ORegMx/servlet/AuthentificationEtud?ident=cin");
        String title1=driver.getTitle();
        if (!(title1.equals("Site de l'inscription universitaire en ligne"))) {
            JOptionPane.showMessageDialog(null,"Verifiez votre connexion internet");
            driver.quit();

        }
        WebElement ele = driver.findElement(By.xpath("//td[@rowspan='2']"));

        driver.manage().timeouts().implicitlyWait(1, TimeUnit.SECONDS);
        // Get entire page screenshot
        File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
        BufferedImage  fullImg = ImageIO.read(screenshot);

        // Get the location of element on the page
        org.openqa.selenium.Point point = ele.getLocation();

        // Get width and height of the element
        int eleWidth = ele.getSize().getWidth();
        int eleHeight = ele.getSize().getHeight();

        // Crop the entire page screenshot to get only element screenshot
        BufferedImage eleScreenshot= fullImg.getSubimage(point.getX(), point.getY(),
            eleWidth, eleHeight);
        ImageIO.write(eleScreenshot, "png", screenshot);

        // Copy the element screenshot to disk
        File screenshotLocation = new File("temp\\captcha.png");
        FileUtils.copyFile(screenshot, screenshotLocation); 


        JLabel captcha = new JLabel("");
        captcha.setIcon(new ImageIcon("temp\\captcha.png"));
        captcha.setBounds(574, 304, 182, 50);
        frame.getContentPane().add(captcha);




        JButton valider = new JButton("Valider");
        valider.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {




                WebElement c = driver.findElement(By.name("cin"));
                WebElement d = driver.findElement(By.id("dn"));
                WebElement cap = driver.findElement(By.name("cincap"));

                String myPass=String.valueOf(CIN.getPassword());
                String date = daten.getText();
                String capp = code.getText();

                // fill the fields
                c.sendKeys(myPass);
                d.sendKeys(date);
                cap.sendKeys(capp);

                // button valider
                cap.submit();



                // check the title of the page
                String title=driver.getTitle();
                if (title.equals("Dashboard - Inscription universitaire en ligne")) {
                    WebElement msg = driver.findElement(By.xpath("/html[1]/body[1]/table[1]/tbody[1]/tr[1]/td[1]/table[1]/tbody[1]/tr[1]/td[1]/table[1]/tbody[1]/tr[1]/td[1]/table[2]/tbody[1]/tr[1]/td[1]/div[1]/div[2]/div[1]/table[1]/tbody[1]/tr[1]/td[1]/div[1]/p[1]"));
                    String name=msg.getAttribute("innerText");
                    //System.out.println(error);
                    String ids = driver.findElement(By.name("Idsession")).getAttribute("value");
                    private String getID() 
                    {
                        return ids;
                    }
                //  String cookie=ids.getAttribute("innerText");
                    //JOptionPane.showMessageDialog(null,ids,"Bienvenue", JOptionPane.INFORMATION_MESSAGE);

                    JOptionPane.showMessageDialog(null,name,"Bienvenue", JOptionPane.INFORMATION_MESSAGE);

                //System.out.println("Bienvenue");   //modify to new frame soon
                    frame.dispose();
                    Accueil bien=new Accueil();
                    bien.setVisible(true);
                // driver.manage().timeouts().implicitlyWait(8, TimeUnit.SECONDS);
                }
                else {
                    WebElement msg = driver.findElement(By.xpath("/html[1]/body[1]/table[1]/tbody[1]/tr[1]/td[1]/table[1]/tbody[1]/tr[1]/td[1]/div[1]/blockquote[1]/div[1]/font[1]"));
                    String error=msg.getAttribute("innerText");
                    //System.out.println(error);
                    JOptionPane.showMessageDialog(null,error);



                    WebElement ele = driver.findElement(By.xpath("//td[@rowspan='2']"));
                    driver.manage().timeouts().implicitlyWait(1, TimeUnit.SECONDS);
                    // Get entire page screenshot
                    File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
                    BufferedImage fullImg = null;
                    try {
                        fullImg = ImageIO.read(screenshot);
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                    // Get the location of element on the page
                    org.openqa.selenium.Point point = ele.getLocation();

                    // Get width and height of the element
                    int eleWidth = ele.getSize().getWidth();
                    int eleHeight = ele.getSize().getHeight();

                    // Crop the entire page screenshot to get only element screenshot
                    BufferedImage eleScreenshot= fullImg.getSubimage(point.getX(), point.getY(),
                        eleWidth, eleHeight);
                    try {
                        ImageIO.write(eleScreenshot, "png", screenshot);
                    } catch (IOException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    }

                    // Copy the element screenshot to disk
                    File screenshotLocation = new File("temp\\captcha.png");
                    try {
                        FileUtils.copyFile(screenshot, screenshotLocation);
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }       



                    ImageIcon img=new ImageIcon("temp\\captcha.png");
                    img.getImage().flush();
                    captcha.setIcon(img);


                }


            }

        });



        valider.setFont(new Font("Tahoma", Font.BOLD, 13));
        valider.setBounds(686, 462, 162, 32);
        frame.getContentPane().add(valider);

        code = new JTextField();
        code.setBackground(new Color(248, 248, 255));
        code.setForeground(Color.BLACK);
        code.setFont(new Font("Helvetica", Font.PLAIN, 18));
        code.setColumns(10);
        code.setBounds(764, 304, 206, 50);
        frame.getContentPane().add(code);

                title_1 = new JLabel("");
                title_1.setIcon(new ImageIcon(title));
                title_1.setBounds(45, 138, 440, 90);
                frame.getContentPane().add(title_1);

        lblVersionBeta = new JLabel("Version Beta");
        lblVersionBeta.setFont(new Font("Tahoma", Font.BOLD, 11));
        lblVersionBeta.setForeground(Color.WHITE);
        lblVersionBeta.setBounds(49, 201, 104, 14);
        frame.getContentPane().add(lblVersionBeta);

        JPanel panel = new JPanel();
        panel.setBackground( new Color(0, 0, 0, 90) );
        panel.setBounds(0, 0, 511, 735);
        frame.getContentPane().add(panel);




        background = new JLabel("");
        //BufferedImage bg = ImageIO.read(new File("./resources/img/AnimationV.gif"));

        URL bg =getClass().getResource("/images/AnimationV.gif");

        // getClass().getResource("resources/img/AnimationV.gif");
        //Image image = Toolkit.getDefaultToolkit().getImage(url);
        //java.io.InputStream image = ClassLoader.getSystemResourceAsStream( "resources/img/AnimationV.gif" );

        background.setIcon(new ImageIcon(bg));
        background.setBounds(0, 0, 1006, 724);
        frame.getContentPane().add(background);



    }
}

2 个答案:

答案 0 :(得分:0)

不能在方法内部创建方法。 您必须在外部 中声明getIds() 像这样...

           public class name {

     private String ids = "";

    public static  void main(String arg[]){

       if (title.equals("***")) {
      // reinitialize id  when title is  equals '***'
    ids =driver.findElement(
By.name("Idsession")) .getAttribute("value");
  }

      String newThing = getID();
      //use it
      }

      // method declaration here

          public String getID() {
            return ids; 
           } 

   }

答案 1 :(得分:0)

我找到了一种方法,可以将输出存储到txt文件中,然后在需要时使用它,谢谢@ shahril772的帮助