第十章 SeleniumWebDrive-高级

第九章 SeleniumWebDrive-高级

1.日历中日期选择(1.点击弹出日历选择框直接点击选择日期2.遍历日历中的日期并选择一个)
package jssd;

import java.util.List;
import java.util.concurrent.TimeUnit;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class calendarclickDemo {

    private WebDriver driver;
    private String baseUrl;

    @Before
    public void setUp() throws Exception {
        driver = new ChromeDriver();
        baseUrl = "https://www.expedia.cn";

        // Maximize the browser's window
        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
    }

    public void test1() throws Exception {
        driver.get(baseUrl);
        // 查找入住文本框
        WebElement checkInField = driver.findElement(By.xpath("//input[@id='hotel-checkin-hp-hotel']"));
        // 点击入住文本框
        checkInField.click();
        Thread.sleep(3000);
        // 查找日期元素
        WebElement dateToSelect = driver.findElement(By.xpath("//caption[contains(text(),'十二月')]//parent::table//button[text()='31']"));
        // 点击日期
        dateToSelect.click();
    }

    @Test
    public void test2() throws Exception {
        driver.get(baseUrl);
        // 查找入住文本框
        WebElement checkInField = driver.findElement(By.xpath("//input[@id='hotel-checkin-hp-hotel']"));
        // 点击入住文本框
        checkInField.click();
        Thread.sleep(3000);
        // 查找日期元素
        WebElement calMonth = driver.findElement(By.xpath("//caption[contains(text(),'十二月')]//parent::table"));
        List<WebElement> allValidDated = calMonth.findElements(By.xpath("//button[@class='datepicker-cal-date']"));
        for(WebElement date:allValidDated){
            if (date.getText().equals("31")){
                date.click();
                break;
            }
        }
    }

    @After
    public void tearDown() throws Exception {
        Thread.sleep(3000);
        driver.quit();
    }

}
2.搜索自动拓展选择(定位ul并遍历)
package jssd;

import org.checkerframework.checker.units.UnitsTools;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author 96510
 * @version 1.0
 * @date 2021/6/29
 */
public class AutoComplete {
    WebDriver driver;
    String url;

    @Before
    public void setUp() throws Exception {
        driver = new ChromeDriver();
        url= "https://www.expedia.com/cn/";
        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
    }

    @Test
    public void name() throws InterruptedException {
        driver.get(url);
        String model = "北京天安门皇家驿栈";
        WebElement e1 = driver.findElement(By.xpath("//button[@data-stid='location-field-destination-menu-trigger']"));
        e1.click();
        Thread.sleep(2000);
        driver.findElement(By.xpath("//input[@id='location-field-destination']")).sendKeys("北京天安门");
        WebElement es = driver.findElement(By.xpath("//ul[@class='uitk-typeahead-results no-bullet']"));
        List<WebElement> eslist = es.findElements(By.xpath("//ul[@class='uitk-typeahead-results no-bullet']//strong"));
        for (WebElement e:eslist){
            if (e.getText().equals(model)){
                e.click();
            }
        }
        driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
    }

    @After
    public void tearDown() throws Exception {
        System.out.println("Test执行后");
    }


}
3.使用JavaScript命令打开一个网站
package jssd;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

import javax.xml.bind.Element;
import java.util.concurrent.TimeUnit;

/**
 * @author 96510
 * @version 1.0
 * @date 2021/6/29
 */
public class JavaScriptExecution {
    WebDriver driver;
    String url;
    private JavascriptExecutor js;

    @Before
    public void setUp() throws Exception {
        driver = new ChromeDriver();
        js = (JavascriptExecutor) driver;
        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);
    }

    @Test
    public void name() throws InterruptedException {
       //打开网站
       js.executeScript("window.location = 'http://www.baidu.com';");
        //使用JS必须等待几秒 driver.get不用
       Thread.sleep(3000);
       WebElement element = driver.findElement(By.id("kw"));
       element.sendKeys("测试");
    }

    @After
    public void tearDown() throws Exception {
        System.out.println("Test执行后");
    }
}
3.使用JavaScript获取窗口的大小
package jssd;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

import java.util.concurrent.TimeUnit;

/**
 * @author 96510
 * @version 1.0
 * @date 2021/6/29
 */
public class JavaScriptExecution {
    WebDriver driver;
    String url;
    private JavascriptExecutor js;

    @Before
    public void setUp() throws Exception {
        driver = new ChromeDriver();
        js = (JavascriptExecutor) driver;
        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
    }

    @Test
    public void name() throws InterruptedException {
        //打开网站
        js.executeScript("window.location = 'http://www.baidu.com';");
        Thread.sleep(3000);
        long width = Long.valueOf(String.valueOf(js.executeScript("return window.innerWidth;")));
        long height = Long.valueOf(String.valueOf(js.executeScript("return window.innerHeight;")));
        System.out.println(width);
        System.out.println(height);
        WebElement element = driver.findElement(By.id("kw"));
        element.sendKeys("测试");
        System.out.println(width);
        System.out.println(height);
    }

    @After
    public void tearDown() throws Exception {
        System.out.println("Test执行后");
    }


}

4.使用JavaScript实现页面滚动
package jssd;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;

import java.util.concurrent.TimeUnit;

/**
 * @author 96510
 * @version 1.0
 * @date 2021/6/29
 */
public class JavaScriptExecution {
    WebDriver driver;
    String url;
    private JavascriptExecutor js;

    @Before
    public void setUp() throws Exception {
        driver = new ChromeDriver();
        js = (JavascriptExecutor) driver;
        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
    }

    @Test
    public void name() throws InterruptedException {
        //打开网站
        js.executeScript("window.location = 'http://www.baidu.com';");
        Thread.sleep(3000);
        long width = Long.valueOf(String.valueOf(js.executeScript("return window.innerWidth;")));
        long height = Long.valueOf(String.valueOf(js.executeScript("return window.innerHeight;")));
        System.out.println(width);
        System.out.println(height);
        driver.findElement(By.id("kw")).sendKeys("测试" + Keys.ENTER);
        Thread.sleep(3000);
        //向下滚动
        js.executeScript("window.scrollBy(0,1900)");
        Thread.sleep(3000);
        //向上滚动
        js.executeScript("window.scrollBy(0,-2000);");
        Thread.sleep(3000);
        WebElement element = driver.findElement(By.xpath("//table[@class='c-gap-bottom-large c-gap-top-xsmall']"));//定位目标位置
        js.executeScript("arguments[0].scrollIntoView(true);", element);//将目标位置与浏览器的顶部对齐
         //js.executeScript("arguments[0].scrollIntoView(false);", element);将目标位置与浏览器的底部对齐
        Thread.sleep(3000);
//        向上滚动
        js.executeScript("window.scrollBy(0,-2000);");
    }

    @After
    public void tearDown() throws Exception {
        System.out.println("Test执行后");
    }
}
5.web页面截图
package jssd;

import java.io.File;
import java.util.concurrent.TimeUnit;
import org.apache.commons.io.FileUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class Screenshots {

	private WebDriver driver;
	private String baseUrl;

	@Before
	public void setUp() throws Exception {
		driver = new ChromeDriver();
		baseUrl = "https://login.yahoo.com";

		// Maximize the browser's window
		driver.manage().window().maximize();
		driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
	}

	@Test
	public void testScreenshots() throws Exception {
		driver.get(baseUrl);
		driver.findElement(By.id("login-username")).sendKeys("test");
		driver.findElement(By.id("login-signin")).click();

	}

	public static String getRandomString(int length) {
		StringBuilder sb = new StringBuilder();
		String characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
		for (int i = 0; i < length; i++) {
			int index = (int) (Math.random() * characters.length());
			sb.append(characters.charAt(index));
		}
		return sb.toString();
	}

	@After
	public void tearDown() throws Exception {
		Thread.sleep(3000);
		String fileName = getRandomString(10)+".png";
		String directory = "D:\\screenshot\\";
		File sourceFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
        //将driver强制转换为TakesScreenshot类型并使用截图功能
		FileUtils.copyFile(sourceFile, new File(directory+fileName));
        //将文件复制出来
		driver.quit();
	}

}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
<h3>回答1:</h3><br/>以下是使用Python编写的K-means算法数据挖掘第十章习题的代码: ``` import numpy as np from matplotlib import pyplot as plt from sklearn.cluster import KMeans %matplotlib inline # 生成随机数据 num_points = 200 num_clusters = 4 x, y = [], [] for i in range(num_points): if np.random.random() > 0.5: x.append(np.random.normal(0.0, 0.9)) y.append(np.random.normal(0.0, 0.9)) else: x.append(np.random.normal(3.0, 0.5)) y.append(np.random.normal(1.0, 0.5)) data = np.column_stack((x, y)) # 执行k-means算法 kmeans = KMeans(n_clusters=num_clusters, init='k-means++', max_iter=100, n_init=1, verbose=0) kmeans.fit(data) # 绘制聚类结果 colors = ['b', 'g', 'r', 'c', 'm', 'y', 'k'] for i in range(num_points): plt.scatter(data[i, 0], data[i, 1], s=30, color=colors[kmeans.labels_[i]]) plt.scatter(kmeans.cluster_centers_[:, 0], kmeans.cluster_centers_[:, 1], marker='x', s=200, linewidths=3, color='k') plt.show() ``` 该代码用于生成随机数据,并执行K-means算法进行聚类。最终绘制聚类结果,并以黑色十字形显示聚类心点。可以通过修改随机数据的生成方式、聚类数目、算法参数等,来测试不同的聚类效果。 <h3>回答2:</h3><br/>K-means算法是一种常用的基于聚类的数据挖掘算法,可以对无标签数据进行聚类分析,本章介绍了K-means算法的原理及其python代码实现。代码如下: ``` python import numpy as np import pandas as pd import matplotlib.pyplot as plt # 生成数据集 def create_datset(k, n): data = [] for i in range(k): init_center = np.random.randint(0, 30, size=2) x = np.random.normal(init_center[0], 1, size=(n, 2)) data.append(x) return np.vstack(data) # 计算欧氏距离 def distance(x, center): diffs = x - center return np.sqrt(np.sum(diffs ** 2, axis=1)) # k-means算法 def k_means(data, k, max_iter=100): # 随机初始化k个心点 centers = data[np.random.choice(data.shape[0], k, replace=False)] for i in range(max_iter): # 计算每个样本距离最近的心点 labels = np.argmin([distance(data, center) for center in centers], axis=0) # 更新心点位置 new_centers = [data[labels == j].mean(axis=0) for j in range(k)] # 判断聚类是否已经收敛,如果已经收敛则退出循环 if np.all(centers == new_centers): break centers = new_centers return centers, labels # 显示聚类结果 def plot_clusters(data, labels, centers): plt.scatter(data[:, 0], data[:, 1], c=labels, s=50, alpha=0.5) plt.scatter(centers[:, 0], centers[:, 1], marker='*', c='r', s=100, alpha=0.5) plt.show() if __name__ == '__main__': data = create_datset(k=3, n=100) centers, labels = k_means(data, k=3) plot_clusters(data, labels, centers) ``` 代码首先生成了一个带有3个簇的数据集,然后通过k_means()函数实现了K-means算法的聚类过程,最后使用plot_clusters()函数将聚类结果可视化展示了出来。 K-means算法的python实现代码较为简单,但需要注意一些细节问题。例如,在实现距离计算时,我们可以使用numpy的sum()函数,但此时需要指定axis参数,否则无法正确计算每个样本距离每个心点的距离;在更新心点位置时,需要注意对样本进行筛选以避免无效计算;同时,在K-means算法的循环过程,需要判断聚类是否已经收敛,并根据需要设置收敛的迭代次数。 <h3>回答3:</h3><br/>k-means算法是一种常用的聚类算法,在数据挖掘得到广泛应用。它的原理简单,是一种迭代算法,不断将数据点分配到离它最近的心点所在的簇,然后重新计算每个簇的心点,直到满足停止条件为止。以下是k-means算法的python代码。 首先,需要导入必要的库和数据集。常用的数据集有iris、wine、digits等。在这里以iris数据集为例。代码如下: ```python from sklearn.datasets import load_iris from sklearn.cluster import KMeans iris = load_iris() X = iris.data ``` 确定簇的个数k,本例将k设为3。 ```python k = 3 ``` 实例化k-means算法模型,并设置参数。n_clusters为簇的个数,init表示初始化的方法,k-means++为默认值,max_iter表示最大的迭代次数,n_init为选取不同的初始化方式运行k-means算法的次数,verbose表示是否输出冗长的进度信息。 ```python kmeans = KMeans(n_clusters=k, init='k-means++', max_iter=100, n_init=10, verbose=0) ``` 训练模型并进行预测。 ```python pred = kmeans.fit_predict(X) ``` 最后,可视化聚类结果。 ```python import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D # 以三个特征为坐标轴画图 fig = plt.figure(1, figsize=(8, 6)) ax = Axes3D(fig, elev=-150, azim=110) ax.scatter(X[:, 0], X[:, 1], X[:, 2], c=pred, cmap=plt.cm.Set1, edgecolor='k', s=40) ax.set_title("iris 3D clustering") ax.set_xlabel("feature 1") ax.w_xaxis.set_ticklabels([]) ax.set_ylabel("feature 2") ax.w_yaxis.set_ticklabels([]) ax.set_zlabel("feature 3") ax.w_zaxis.set_ticklabels([]) plt.show() ``` 以上是k-means算法的python代码,在实际应用,可以根据数据集的特点选择合适的簇数和参数,得到更好的聚类效果。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值