I am participating in the Mid-Autumn Festival Creative Submission contest, please see: Mid-Autumn Festival Creative Submission Contest for details

Have a dream?

The thing is, might be a little hot, in the morning wake up early, the author has accumulated in signed in 61, the Denver nuggets clock in 58 times in a row, the daily practice, check-in and lottery free again, can say goodbye, but today saw wheel prizes not ah, have replaced several awards in Mid-Autumn festival gift box, but also don't need to unlock the oh. The nuggets can still do this. So the author in addition to consumption of 2W + drill, there are 4.8+ W drill, can you draw, think about a little excited?Copy the code

To behave

How to say 4.8+ W drill point by hand, then I went to, roughly calculated 200 drill/time, need to click 200+ times, OMG, fingers have to break, give up? But the Mid-Autumn Festival gift box is so tempting; It occurred to me that digg had written all kinds of articles about sweepstakes before, but I wanted something different. I just sat quietly on my computer, which automatically sweepstakes and enjoyed the process, although... Ahem... It doesn't matter if you can't draw it. Let's hope the Nuggets take it easy.Copy the code

The preparatory work

Ideas need action to get results, not fantasy!

Environment Deployment (omitted)
This time use Java + Selenium to implement this somewhat exciting automation script; The installation process is omitted, a little too basic, sorry to take out the words ^-^.Copy the code
Script design

I wanted to write it as a linear script, just once, so I didn't want to spend too much time; However, a recent review of Java + Selenium design UI automation testing framework; Also want to shun bring practice hand, to help improve their memory; So use PageFactory design pattern; Why not use PO? Because it is a test design pattern, it does not interact with any tools or frameworks, and is purely selenium's secondary encapsulation of the business.

Before you start writing the script, ask two questions:

  • Login status. How do I get around this step?
  • The processing of the business logic, for example, how many times to loop?
Code implementation
There are several solutions to the first problem. Since the login requires a slider verification code, you can write complex Java code to calculate the location of the bump and drag the image. This is too troublesome, so it is decisively abandoned. The second method is to log in manually first and save the cookies. This sounds good, but the implementation is a bit cumbersome (in contrast to Python); So the idea is: automatically get cookies save automatically read cookiesCopy the code

The first step is to automatically open the browser to obtain cookie and save to TXT file, the second part is to read cookie information in TXT, add to cookie and refresh the page, that is, login is successful

public class IndexPage {

	// Initialize the driver object
	private WebDriver driver;

	// Initialize the page element
	public IndexPage(WebDriver driver) {
		this.driver = driver;
		PageFactory.initElements(driver, this);
		// PageFactory.initElements(new AjaxElementLocatorFactory(driver,
		// TIMEOUT), this);
	}

	@FindBy(css = ".first-line>button")
	@CacheLookup
	/ / cache
	WebElement signIn;

	@ FindBy (xpath = "/ / div [@ id = 'juejin'] / / div [contains (text ()," lucky draw ")] ")
	@CacheLookup
	List<WebElement> luckyLottery;

	@findby (xpath = "//div[contains(text(),' times ')]")
	@CacheLookup
	WebElement cost;

	@FindBy(css = "span.value")
	@CacheLookup
	WebElement value;

	@findby (xpath = "button[text()=' look ']")
	@CacheLookup
	WebElement toSee;

	@findby (xpath = "button[text()=' jump '])
	@CacheLookup
	WebElement jumping;

	/** * open the browser, there is a cookie in the middle, and then refresh the page **@throws Exception
	 */
	public void OpenBrowser(a) throws Exception {
		driver.manage().window().maximize();
		driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
		driver.get(Constants.JjinUrl);
		ReadCookieFromText();
		driver.navigate().refresh();
	}

	public void CloseBrowser(a) {
		if(driver ! =null) { driver.quit(); }}/** * This step is complicated, but it needs to check whether there is toast popup; Then click */ step by step
	public void ClickSignIn(a) {
		if (toSee.isDisplayed()) {
			toSee.click();
			jumping.click();
			signIn.click();
		} else{ signIn.click(); }}/** * click the lucky draw, because it has a hidden element, so the list returns, and then decide which element to click to display */
	public void ClickLottery(a) {
		for (WebElement el : luckyLottery) {
			if(el.isDisplayed()) { el.click(); }}}/** * Close the browser if there are no diamonds */
	public void ClickCostLottery(a) {
		if (CheckIsLottery()) {
			waitForClickable(cost);
			cost.click();
		} else {
			driver.quit();
			System.out.println("No diamond raffle. Close your browser."); }}/** * write a generic wait element method **@param element
	 * @throws Error
	 */
	private void waitForVisibility(WebElement element) throws Error {
		new WebDriverWait(driver, 30).until(ExpectedConditions
				.visibilityOf(element));
	}

	/** * clickable element **@param element
	 * @throws Error
	 */
	private void waitForClickable(WebElement element) throws Error {
		new WebDriverWait(driver, 10).until(ExpectedConditions
				.elementToBeClickable(element));
	}

	/** * Check if there are enough diamonds for lucky draw **@return* /
	public boolean CheckIsLottery(a) {
		waitForVisibility(value);
		int v = Integer.parseInt(value.getText());
		System.out.println(v);
		if (v < 200) {
			return false;
		}
		return true;
	}

	/** * This method is used to manually log in to retrieve cookies **@throws Exception
	 */
	public void WriteCookieToText(a) throws Exception {
		driver.get(Constants.JjinUrl);
		Thread.sleep(20000);
		Set<Cookie> cookies = driver.manage().getCookies();
		File cookieFile = new File("cookie.txt");
		cookieFile.delete();
		cookieFile.createNewFile();
		FileWriter fileWriter = new FileWriter(cookieFile);
		BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
		for (Cookie cookie : cookies) {
			bufferedWriter.write(cookie.getDomain() + ";" + cookie.getName()
					+ ";" + cookie.getValue() + ";" + cookie.getExpiry() + ";"
					+ cookie.getPath());
			bufferedWriter.newLine();
		}
		bufferedWriter.flush();
		bufferedWriter.close();
		fileWriter.close();
		driver.quit();
	}

	/** * to read cookie information in TXT and add driver **@throws Exception
	 */
	@SuppressWarnings({ "resource", "deprecation" })
	public void ReadCookieFromText(a) throws Exception {
		BufferedReader bufferedReader;
		File cookieFile = new File("cookie.txt");
		FileReader fileReader = new FileReader(cookieFile);
		bufferedReader = new BufferedReader(fileReader);
		String line;
		while((line = bufferedReader.readLine()) ! =null) {
			StringTokenizer stringTokenizer = new StringTokenizer(line, ";");
			while (stringTokenizer.hasMoreTokens()) {
				String domain = stringTokenizer.nextToken();
				String name = stringTokenizer.nextToken();
				String value = stringTokenizer.nextToken();
				Date expiry = null;
				String dt;
				if(! (dt = stringTokenizer.nextToken()).equals("null")) {
					expiry = new Date(dt);
				}
				String path = stringTokenizer.nextToken();
				Cookie cookie = newCookie(name, value, domain, path, expiry); driver.manage().addCookie(cookie); }}}/** * Lucky draw business flow: want to draw several times can be controlled here **@throws Exception
	 */
	public void Lottery(a) throws Exception {
		OpenBrowser();
		ClickSignIn();
		ClickLottery();
		ClickCostLottery();
		Thread.sleep(10000);
		CloseBrowser();
	}

	/** * program execution entry, no further test cases **@param args
	 * @throws Exception
	 */
	public static void main(String[] args) throws Exception {
		System.setProperty("webdriver.chrome.driver", Constants.driverUrl);
		WebDriver driver = new ChromeDriver();
		driver.manage().window().maximize();
		driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);

		IndexPage index = newIndexPage(driver); index.Lottery(); }}Copy the code

conclusion

Comrades, take note: When obtaining login cookie information manually, the position of the written and read cookie must match, do not write path in front of domain, read domain is in front of path, so read out the data is wrong, even if addcookie is wrong. Besides, there is a parameter of type date, so the position is important.

  • The second problem is that due to time constraints, the testng framework is not introduced to write use cases. Instead, it is simply implemented in the current main method. You can get the total number of diamonds and then /200 to get the number of lucky draws. You can get 66 diamonds in the lottery and then draw them again.
  • The key point, there is a small technical point, because the operation speed is too fast, some elements are not loaded before the operation, may fail, directly pass to close the browser. So also according to the condition to join the display wait mechanism!
  • Finally, hope to win, Mid-Autumn festival gift box, I wish you guys high school!! Nuggets big guys, send gift box!!