java-获取1688网站商家信息----简单应用

1.下载google浏览器

        注: 苹果电脑下载 旧版本google浏览器 点设置时会自动更新, (卸载重装),运行时版本和驱动不匹配会报错

第三方网站下载链接:旧版本(安装后老是提示更新,最新版本没有找到对应的驱动,不能更新它)

        Google Chrome 64bit OS X版_chrome浏览器,chrome插件,谷歌浏览器下载,谈笑有鸿儒

查看浏览器版本 在地址栏输入:        chrome://version/        

2.下载ChromeDrever  驱动,对应浏览器的版本下载解压即可

        CNPM Binaries Mirror

3.需要代理 不然老是提示你要登录

        作者用的是         快代理 - 企业级HTTP代理IP云服务_专注IP代理10年

        或者不用代理 自己试试试看

4.创建项目:  maven项目 

        需要用到插件 :        Selenium

        maven仓库:        https://mvnrepository.com/

        文档说明:        Selenium 浏览器自动化项目 | Selenium

        相关教程:        哔哩哔哩_bilibili

4.1创建项目: 

        jdk  用的11 ,  1.8 的也没问题,其他版本没用过

       

4.2 添加插件: 找到 pom.xml

               

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>Demo</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java -->
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>4.11.0</version>
        </dependency>
        

        <!-- SLF4J API  打印日志的-->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.30</version> <!-- 使用最新的稳定版本 -->
        </dependency>
        <!--  Logback Classic (contains SLF4J binding) and Core -->
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.2.3</version> <!-- 使用最新的稳定版本 -->
        </dependency>

    </dependencies>
    <dependencyManagement>
        <dependencies>

        </dependencies>
    </dependencyManagement>

</project>

        

4.3简单的封装下代码 工具类:

package org.example;

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.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.time.Duration;
import java.util.Set;

public class Util {

    public Util(String keyword, int index, int len) {
        getContacts(keyword,index,len);
    }

    /**
     * @param keyword 关键字
     * @param index 0
     * @param len 几条数据
     * @return
     */
    public static void getContacts(String keyword, int index, int len) {
        for (; index < len; index++) {


            // 1.找驱动 设置ChromeDriver的路径  填绝对路径 winds d:/某某目录下/chromedriver.exe
            System.setProperty("webdriver.chrome.driver", "/Users/Desktop/javaGHui/Chromedriver/chromedriver");

            // 创建ChromeOptions对象
//        ChromeOptions options = new ChromeOptions();
//        // 设置代理
//        Proxy proxy = new Proxy();
//        proxy.setHttpProxy("***.***.com:***"); // 设置你的代理主机和端口
//        proxy.setSslProxy("***.***.com:***"); // 对于HTTPS代理,也进行设置
            // 如果你有代理的用户名和密码,可以这样设置
//             proxy.setProxyType(Proxy.ProxyType.MANUAL);
//             proxy.setAutodetect(false);
//             proxy.setSslProxyUsername("username");
//             proxy.setSslProxyPassword("password");

            // 将代理设置添加到ChromeOptions
//        options.setCapability("proxy", proxy);
            //2.把代理添加到驱动
            // WebDriver driver = new ChromeDriver(options);

            //2.或者不使用代理
            WebDriver driver = new ChromeDriver();
            String url = "https://s.1688.com/selloffer/offer_search.htm?keywords=" + keyword + "&n=y&netType=1%2C11%2C16&spm=a260k.dacugeneral.search.0";
            try {
                // 设置浏览器窗口大小(可选)
                //driver.manage().window().setSize(new org.openqa.selenium.Dimension(1280, 1024));
                //输入网址
                driver.get(url);


                //找公司   [1-60] 个 一页数据
                String xpathExpression = "//*[@id=\"sm-offer-list\"]/div[" + index + "]/div/div[1]/div/a";
                WebElement gonsilinkElement = driver.findElement(By.xpath(xpathExpression));

                // 等待搜索框可见
                // 等待搜索结果加载(这里可以根据实际情况调整等待条件和时间)
                long minutes = 10;
                Duration duration = Duration.ofMinutes(minutes);
                WebDriverWait gongsiwait = new WebDriverWait(driver, duration);// 设置超时时间为10秒
                 等待直到a标签变得可点击
                gongsiwait.until(ExpectedConditions.elementToBeClickable(gonsilinkElement));

                // 检查是否找到了元素
                if (gonsilinkElement != null) {
                    // 点击a标签
                    System.out.println("找到匹配的a标签" + gonsilinkElement);
                    gonsilinkElement.click();

                    // 这里可以添加代码来处理点击后的页面行为
                } else {
                    System.out.println("没有找到匹配的gonsilinkElement标签");
                }


                // 获取所有窗口句柄
                Set<String> windowHandles = driver.getWindowHandles();
                // 切换到新打开的窗口
                for (String windowHandle : windowHandles) {
                    if (!windowHandle.equals(driver.getWindowHandle())) {
                        driver.switchTo().window(windowHandle);
                        break;
                    }
                }

                //找联系电话
                WebElement linkElement = driver.findElement(By.xpath("//a[text()='联系方式']"));

                 等待直到a标签变得可点击
                gongsiwait.until(ExpectedConditions.elementToBeClickable(linkElement));

                // 检查是否找到了元素
                if (linkElement != null) {
                    // 点击a标签
                    System.out.println("找到匹配的的联系电话标签" + linkElement);
                    linkElement.click();

                    // 这里可以添加代码来处理点击后的页面行为
                } else {
                    System.out.println("没有找到匹配的联系电话标签");
                }

                // 标记是否为最后一次迭代
                int i = 0;
                // 切换到新打开的窗口
                Set<String> windowHandlesss = driver.getWindowHandles();

                System.out.println("窗口长度:" + driver.getWindowHandles().size());

                for (String windowHandle : windowHandlesss) {
                    i++;
                    System.out.println(i + "窗口windowHandle" + windowHandle);

                    if (i == 3) {
                        driver.switchTo().window(windowHandle);

                    }

                }


                //保存联系人
                // 获取网页的根元素
                WebElement rootElement = driver.findElement(By.tagName("html"));

                // 使用JavaScript获取网页的完整HTML
                // JavascriptExecutor js = (JavascriptExecutor) driver;
                // String htmlContent = (String) js.executeScript("return document.documentElement.outerHTML;");

                // 提取网页中的文本数据
                String textContent = rootElement.getText();

                // 查找开始位置的索引
                int startIndex = textContent.indexOf("联系方式") + "联系方式".length();

                // 查找结束位置的索引
                int endIndex = textContent.indexOf("有任何问题欢迎电话或在线沟通咨询,欢迎实地考察!");

                // 使用substring方法提取子串
                if (endIndex != -1) {
                    String substring = textContent.substring(startIndex, endIndex);


                    // 保存到本地文件
                    saveToFile2("webContacts.txt", substring);


                    // 如果需要,还可以保存完整的HTML内容
                    // saveToFile("webpage_html.html", htmlContent);

                } else {
                    System.out.println("开始或结束位置未找到");
                }


            } catch (Exception e) {
                e.printStackTrace();
                System.err.println("出错了");
            } finally {
                //最后确保关闭所有剩余窗口并退出WebDriver
                driver.quit();
            }

        }

    }


    /**
     * 保存文件方法
     */
    private static void saveToFile(String fileName, String content) {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(fileName))) {
            writer.write(content);
            System.out.println("文件 " + fileName + " 已保存。");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 保存文件方法 追加文本
     */
    public static void saveToFile2(String fileName, String content) {
        FileWriter fileWriter = null;
        BufferedWriter bufferedWriter = null;

        try {
            // 创建 FileWriter 对象,用于写入字符流,true 表示追加模式
            fileWriter = new FileWriter(fileName, true);

            // 创建 BufferedWriter 对象,将 FileWriter 包装起来,提供缓冲功能
            bufferedWriter = new BufferedWriter(fileWriter);

            // 写入内容到文件
            bufferedWriter.write(content);

            // 刷新缓冲区,确保内容被写入文件
            bufferedWriter.flush();
            System.out.println("文件 " + fileName + " 已保存。");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭流
            try {
                if (bufferedWriter != null) {
                    bufferedWriter.close();
                }
                if (fileWriter != null) {
                    fileWriter.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}

4.3 主方法代码:

package org.example;


public class MainDemo {
    public static void main(String[] args) {
        // 搜索框中 要搜索的内容
        // 循环获取 
        Util util = new Util("短袖",0,60);
    }

}

等执行完成 ,打开文件webContacts.txt        就可看到联系电话了

5.学习 定位 网页元素

       http://t.csdnimg.cn/6UcEn

Ai  推荐:

有问题? 请来找我,文心一言
        

  • 4
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Java HttpClient是一种用于发送HTTP请求和接收HTTP响应的开源Java库。它提供了一种简单而灵活的方法来与服务器进行通信,并支持HTTP协议的各种功能,如GET请求、POST请求、Cookie管理等。通过使用Java HttpClient,我们可以方便地与其他应用程序或服务器进行数据交互。 微信投票是指利用微信平台进行投票活动的一种方式。用户可以通过微信公众号或小程序参与投票,并在投票过程中选择自己心仪的选项。微信提供了丰富的开发接口和功能,使得开发者可以快速搭建投票系统,并与用户实时互动。通过合理地使用微信开放平台的相关接口,我们可以实现从投票的创建、选项的展示到结果的统计等一系列投票过程的控制和管理。 User-Agent(用户代理)是HTTP请求头的一部分,用于告知服务器发送请求的客户端类型。在使用Java HttpClient发送HTTP请求时,我们可以通过设置User-Agent头部来模拟不同的客户端类型,以实现自定义的请求行为。例如,我们可以设置User-Agent为移动设备模式,以便服务器返回适配于移动设备的响应。 经纬度是用于表示地球上位置的坐标系统。通过使用经纬度,我们可以确定地球上任何地点的具体位置。在实际应用中,经纬度常用于地图服务、定位服务等。在Java中,可以使用各种第三方库或者服务提供商的API来获取地点的经纬度信息。同时,我们可以通过将经纬度信息与其他数据结合使用,实现一些特定的功能,比如根据用户经纬度提供附近的商家信息等。 总之,Java HttpClient可以用于与服务器进行HTTP通信,微信投票可以在微信平台上进行投票活动,User-Agent可以在发送HTTP请求时模拟不同客户端类型,经纬度是用于确定地球上位置的坐标系统。这些概念在不同的场景和应用中具有重要意义,并且可以通过Java编程来实现相应的功能。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

javaGHui

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值