龙空技术网

使用 Selenium 爬取网页信息

IT小村 184

前言:

此时兄弟们对“java如何爬取网页数据”大概比较着重,看官们都需要知道一些“java如何爬取网页数据”的相关知识。那么小编也在网摘上汇集了一些有关“java如何爬取网页数据””的相关内容,希望小伙伴们能喜欢,大家一起来了解一下吧!

一、前言

Selenium 初衷是做一个自动化测试工具,但是应用在爬虫领域,效果还是相当不错的!

二、安装

selenium驱动下载()版本,注意和本地 Chrome 版本一致,如:

下载完成后,将 selenium 驱动放到 chrome.exe 同级目录下:

三、代码

1.依赖

<dependency>    <groupId>org.seleniumhq.selenium</groupId>    <artifactId>selenium-java</artifactId>    <version>3.141.0</version></dependency>

2.测试

获取百度云信息的案例

import org.openqa.selenium.By;import org.openqa.selenium.WebDriver;import org.openqa.selenium.WebElement;import org.openqa.selenium.chrome.ChromeDriver;import org.openqa.selenium.chrome.ChromeOptions;import org.openqa.selenium.support.ui.ExpectedCondition;import org.openqa.selenium.support.ui.WebDriverWait;import java.util.HashMap;import java.util.Map;public class TestSelenium {   public static void main(String[] args) {       // 本地的驱动地址       System.setProperty("webdriver.chrome.driver", "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chromedriver.exe");       Map<String, Object> preferences = new HashMap<String, Object>();       ChromeOptions options = new ChromeOptions();       // 不加载图片,提高速度       preferences.put("profile.managed_default_content_settings.images", 2);       options.setExperimentalOption("prefs", preferences);       WebDriver driver = new ChromeDriver(options);       // 百度网盘地址       driver.get(";);       // 限制爬取时长       WebDriverWait wait = new WebDriverWait(driver, 5);       wait.until(new ExpectedCondition<Boolean>() {           public Boolean apply(WebDriver d) {               boolean loadcomplete = d.findElement(By.tagName("body")).isDisplayed();               return loadcomplete;           }       });       boolean hasPassword = false; // 是否有密码       String title = driver.getTitle();       if ("百度网盘 请输入提取码".equals(title)) {           hasPassword = true;       }       if (hasPassword) {           WebElement pInput = driver.findElement(By.cssSelector(".QKKaIE.LxgeIt"));           WebElement btn = driver.findElement(By.cssSelector(".g-button-right"));           // 输入密码           pInput.sendKeys("uffx");           // 点击提取           btn.click();       }       System.out.println(title);       // driver.close(); // 浏览器关闭       //  driver.quit(); // 释放资源   }}

标签: #java如何爬取网页数据