selenium firefox 提取qq空间相册链接

时间:2021-10-05 16:16:46

环境:

selenium-java 3.9.1

firefox 57.0

geckodriver 0.19.1

1.大概的思路就是模拟用户点击行为,关于滚动条的问题,我是模拟下拉箭头,否则只能每个相册只能爬到30个链接

2.多开标签页的原因是因为爬取多个相册时,当你爬完第一个相册无论采取什么方式总会导致当前原来的相册列表刷新,从而导致selenium的元素附着失败的异常,所以我的思路是一个相册一个标签页,全部爬取完成后再统一关闭,最开始打开的页面并没有直接用于爬取第一个相册,如果你额外新打开了标签页注意修改for循环中句柄的index

3.使用selenium提取链接效率低下,因为总是要让程序等待页面加载,切换frame,js打开新标签页,句柄切换等页面跳转行为非常耗费时间,链接将按相册名进行保存

4.代码仅供测试,写的并不健壮.严格的讲,只要定位元素就应当try catch,因为drver如果无法find元素就会抛出unlocate异常,没法再去判断元素是否为null了

5.使用前请更改用户名用户密码,如果登录失败,请重新执行,默认登录后等待5s会重新登录

 package selenium.ff;

 import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.apache.commons.io.IOUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.interactions.Actions; /**
* 模拟登录qq空间并保存相册的图片链接
* @author tele
*
*/
public class QZImage {
static final int pageSize = ;
public static void main(String[] args) throws Exception {
System.setProperty("webdriver.gecko.driver", "D:/browserdriver/geckodriver.exe"); FirefoxOptions options = new FirefoxOptions();
options.setBinary("F:/ff/firefox.exe"); WebDriver driver = new FirefoxDriver(options);
driver.manage().window().maximize();
// 超时
try {
driver.manage().timeouts().pageLoadTimeout(, TimeUnit.SECONDS);
driver.manage().timeouts().setScriptTimeout(, TimeUnit.SECONDS);
driver.get("https://i.qq.com/");
} catch (Exception e) {
System.out.println("所需元素已出现,停止加载页面");
} finally {
// 切换到登录login
driver.switchTo().frame("login_frame"); WebElement switcher_plogin = driver.findElement(By.id("switcher_plogin"));
System.out.println(switcher_plogin.getText());
if (switcher_plogin.isDisplayed()) {
switcher_plogin.click();
}
// 用户名
driver.findElement(By.id("u")).clear();
driver.findElement(By.id("u")).sendKeys("******"); // 密码
driver.findElement(By.id("p")).clear();
driver.findElement(By.id("p")).sendKeys("******"); // 登录
try {
driver.findElement(By.id("login_button")).click();
Thread.sleep();
} catch (Exception e) {
e.printStackTrace();
} finally {
if ("https://i.qq.com/".equals(driver.getCurrentUrl())) {
System.out.println("登录失败!5秒后再次尝试登录");
Thread.sleep();
driver.findElement(By.id("login_button")).click();
}
} // 退出frame
driver.switchTo().defaultContent(); System.out.println(driver.getCurrentUrl()); // 点击相册
driver.findElement(By.cssSelector("#menuContainer ul.head-nav-menu>li.menu_item_4>a")).click(); Thread.sleep(); // 切换到frame
driver.switchTo().frame(driver.findElement(By.className("app_canvas_frame"))); JavascriptExecutor jsExecutor = (JavascriptExecutor) driver; // 获得相册列表
List<WebElement> photoList = driver.findElements(By.xpath("//ul[@class='js-album-list-ul']/li"));
if (photoList == null || photoList.size() == ) {
throw new RuntimeException("定位相册列表元素失败!");
} // 构造不同相册的xpath路径
List<String> xpathList = new ArrayList<String>();
for (int i = ; i < photoList.size(); i++) {
xpathList.add("//ul[@class='js-album-list-ul']/li[" + (i + ) + "]");
} // 窗口句柄
List<String> allHandles = new ArrayList<String>(driver.getWindowHandles()); // 遍历xpath
String newUrl = driver.getCurrentUrl();
for (int i = ; i < xpathList.size(); i++) {
// 打开新标签页
String js = "window.open('" + newUrl + "');";
jsExecutor.executeScript(js);
allHandles = new ArrayList<String>(driver.getWindowHandles()); Thread.sleep();
String xpath = xpathList.get(i); // 句柄切换需要时间
driver.switchTo().window(allHandles.get(i + ));
Thread.sleep();
saveImageUrl(driver, xpath);
} System.out.println("所有相册图片链接提取完毕,退出浏览器");
driver.quit(); } } /**
* 提取图片url
*
* @param driver
* @param xpath
* @throws InterruptedException
* @throws IOException
*/
public static void saveImageUrl(WebDriver driver, String xpath) throws InterruptedException, IOException { // 点击相册
driver.findElement(By.cssSelector("#menuContainer ul.head-nav-menu>li.menu_item_4>a")).click(); Thread.sleep(); // 切换到图片的frame
driver.switchTo().frame(driver.findElement(By.className("app_canvas_frame"))); // 获得相册名称
String photo_name = driver.findElement(By.xpath(xpath + "//a[@class='c-tx2 js-album-desc-a']")).getText(); //// 文件夹检测
File imageUrl = new File("f:/qz/" + photo_name + ".txt");
if (!imageUrl.getParentFile().exists()) {
imageUrl.mkdirs();
} else {
imageUrl.delete();
} // 获得图片总数,每页最多98张图片
WebElement span = driver.findElement(By.xpath(xpath + "/div[1]/div[1]/a" + "/span"));
String text = span.getText();
int count = Integer.parseInt(text); // 进入列表
driver.findElement(By.xpath(xpath + "/div[1]/div[1]/a")).click();
Thread.sleep(); // 计算页数
int totalPage = (int) Math.ceil((double) count / (double) pageSize);
System.out.println(photo_name + "图片总数为----" + count + "张,共计---" + totalPage + "页"); FileWriter fileWriter = new FileWriter(imageUrl, true); for (int i = ; i < totalPage; i++) { // 模拟按键加载图片
Actions actions = new Actions(driver);
for (int j = ; j < ; j++) {
if (j % == ) {
Thread.sleep();
}
actions.sendKeys(Keys.ARROW_DOWN).perform();
} // 提取本页的image链接
List<WebElement> list = driver.findElements(By.xpath("//img[@class='j-pl-photoitem-img']"));
if (list == null || list.size() == ) {
// 相册无权限访问或定位失败
throw new RuntimeException("无法提取图片链接!");
}
for (WebElement element : list) {
String src = element.getAttribute("src") + "\n";
IOUtils.write(src, fileWriter);
}
System.out.println("第" + (i + ) + "页图片链接提取完毕"); Thread.sleep(); // 跳转到下一页
if ((i + ) <= totalPage) {
driver.findElement(By.xpath("//a[@id='pager_num_1_" + (i + ) + "']")).click();
}
} fileWriter.close();
}
}