HtmlUnit 是一个用于模拟浏览器行为的 Java 库,可以用于爬取网页内容,包括天猫网站上的图片。以下是一个使用 HtmlUnit 来采集天猫图片的简单示例:
首先,确保你的项目中包含 HtmlUnit 的依赖。你可以使用 Maven 或 Gradle 来添加依赖:
对于 Maven:
<dependency>
<groupId>net.sourceforge.htmlunit</groupId>
<artifactId>htmlunit</artifactId>
http://www.jshk.com.cn/mb/reg.asp?kefu=xiaoding;//爬虫IP免费获取;
<version>2.56.0</version>
</dependency>
对于 Gradle:
implementation 'net.sourceforge.htmlunit:htmlunit:2.56.0'
然后,可以使用以下 Kotlin 代码来实现天猫图片采集:
import com.gargoylesoftware.htmlunit.WebClient
import com.gargoylesoftware.htmlunit.html.HtmlImage
import com.gargoylesoftware.htmlunit.html.HtmlPage
import java.net.URL
fun main() {
// 创建一个 HtmlUnit WebClient 实例
val webClient = WebClient()
// 设置 WebClient 的一些选项,例如启用 JavaScript
webClient.options.isJavaScriptEnabled = true
webClient.options.isCssEnabled = true
try {
// 输入天猫的商品详情页 URL
val tmallProductUrl = "https://detail.tmall.com/item/1234567890.html" // 请替换为实际商品页面的 URL
// 获取页面
val page: HtmlPage = webClient.getPage(tmallProductUrl)
// 获取页面上的所有图片
val images: List<HtmlImage> = page.getByXPath("//img[@src]") as List<HtmlImage>
// 遍历并下载图片
for ((index, image) in images.withIndex()) {
val imageUrl = image.getAttribute("src")
downloadImage(imageUrl, "image_$index.jpg")
}
} finally {
// 关闭 WebClient
webClient.close()
}
}
private fun downloadImage(imageUrl: String, fileName: String) {
try {
val url = URL(imageUrl)
val connection = url.openConnection()
// 下载图片并保存到本地文件
connection.getInputStream().use { input ->
val outputFile = java.io.File(fileName)
java.nio.file.Files.copy(input, outputFile.toPath(), java.nio.file.StandardCopyOption.REPLACE_EXISTING)
println("Downloaded: $fileName")
}
} catch (e: Exception) {
e.printStackTrace()
}
}
请注意,你需要将 tmallProductUrl 替换为实际天猫商品详情页的 URL。此示例假设商品详情页上的图片使用 <img> 标签,并通过 XPath 表达式 //img[@src] 获取所有图片元素。你可能需要根据实际情况修改 XPath 表达式以匹配天猫网站的结构。