当前位置: 首页 > news >正文

进地铁建设公司网站关键词排名推广

进地铁建设公司网站,关键词排名推广,网站建站推广,游戏编辑器WebScraper 工具类使用手册 序言#xff1a; java简单易用的封装爬虫工具类#xff0c;代码和案例奉上#xff0c;把你的点击和收藏也一并奉上吧[狗头#x1f47b;]#xff0c; springboot版本#xff1a;3.4.5 java版本#xff1a;17 安装依赖#xff1a; pr…WebScraper 工具类使用手册 序言 java简单易用的封装爬虫工具类代码和案例奉上把你的点击和收藏也一并奉上吧[狗头] springboot版本3.4.5 java版本17 安装依赖 propertiesjava.version17/java.versionmaven.compiler.source11/maven.compiler.sourcemaven.compiler.target11/maven.compiler.targetselenium.version4.20.0/selenium.version !-- Check for latest Selenium version --webdrivermanager.version5.8.0/webdrivermanager.version !-- Check for latest WebDriverManager version --gson.version2.10.1/gson.version !-- Check for latest Gson version --/propertiesdependencies!-- Selenium Java --dependencygroupIdorg.seleniumhq.selenium/groupIdartifactIdselenium-java/artifactIdversion${selenium.version}/version/dependency!-- WebDriverManager --dependencygroupIdio.github.bonigarcia/groupIdartifactIdwebdrivermanager/artifactIdversion${webdrivermanager.version}/version/dependency!-- JSON Processing (Gson) --dependencygroupIdcom.google.code.gson/groupIdartifactIdgson/artifactIdversion${gson.version}/version/dependency!-- SLF4J Simple Logger (for less verbose Selenium logging) --dependencygroupIdorg.slf4j/groupIdartifactIdslf4j-simple/artifactIdversion2.0.12/version !-- Or a version compatible with your Selenium --/dependency/dependencies1. 类名WebScraper 功能封装了浏览器控制、页面交互和数据提取的核心功能提供灵活易用的爬虫框架。 2. 初始化方法 方法签名__init__(browser_typechrome, headlessTrue, user_agentNone, proxyNone, timeout30, debugFalse) 功能初始化爬虫实例配置浏览器和开发工具 参数说明 browser_type浏览器类型可选值chrome, firefox, edgeheadless是否以无头模式运行浏览器user_agent自定义 User-Agent 字符串proxy代理服务器配置格式{http: http://proxy.example.com:8080, https: http://proxy.example.com:8080}timeout操作超时时间秒debug是否开启调试模式 3. 浏览器控制方法 3.1 open_url(url) 功能打开指定 URL参数url - 目标 URL返回页面加载完成状态 3.2 close() 功能关闭浏览器实例参数无 3.3 refresh() 功能刷新当前页面参数无 3.4 go_back() 功能返回上一页参数无 4. 元素定位与交互方法 4.1 find_element(selector, by“css”, timeoutNone) 功能查找单个元素 参数 selector选择器字符串by选择器类型可选值css, xpath, id, class, name, link_text, partial_link_text, tag_nametimeout等待元素出现的超时时间秒 返回找到的元素对象或 None 4.2 find_elements(selector, by“css”, timeoutNone) 功能查找多个元素参数同find_element返回找到的元素列表 4.3 click(elementNone, selectorNone, by“css”, timeoutNone) 功能点击元素 参数 element元素对象优先使用selector选择器字符串当 element 为 None 时使用by选择器类型timeout等待元素出现的超时时间 返回操作结果 4.4 type_text(text, elementNone, selectorNone, by“css”, timeoutNone, clear_firstTrue) 功能在输入框中输入文本 参数 text要输入的文本element元素对象优先使用selector选择器字符串当 element 为 None 时使用by选择器类型timeout等待元素出现的超时时间clear_first是否先清空输入框 返回操作结果 5. 滚动方法 5.1 scroll(direction“down”, amountNone, elementNone, smoothTrue, duration0.5) 功能滚动页面或元素 参数 direction滚动方向可选值up, down, left, rightamount滚动量像素默认为页面高度 / 宽度的 50%element要滚动的元素默认为整个页面smooth是否平滑滚动duration滚动持续时间秒 返回操作结果 5.2 scroll_to_element(elementNone, selectorNone, by“css”, timeoutNone, align“center”) 功能滚动到指定元素 参数 element元素对象优先使用selector选择器字符串当 element 为 None 时使用by选择器类型timeout等待元素出现的超时时间align元素对齐方式可选值top, center, bottom 返回操作结果 5.3 scroll_to_bottom(elementNone, steps10, delay0.5) 功能滚动到页面或元素底部 参数 element要滚动的元素默认为整个页面steps滚动步数delay每步之间的延迟秒 返回操作结果 6. 翻页方法 6.1 next_page(selectorNone, method“click”, url_templateNone, page_param“page”, next_page_funcNone) 功能翻到下一页 参数 selector下一页按钮的选择器当 method 为 “click” 时使用method翻页方法可选值click, url, functionurl_templateURL 模板当 method 为 “url” 时使用page_param页码参数名当 method 为 “url” 时使用next_page_func自定义翻页函数当 method 为 “function” 时使用 返回翻页是否成功 6.2 has_next_page(selectorNone, check_funcNone) 功能检查是否有下一页 参数 selector下一页按钮的选择器check_func自定义检查函数 返回布尔值表示是否有下一页 6.3 set_page(page_num, url_templateNone, page_param“page”) 功能跳转到指定页码 参数 page_num目标页码url_templateURL 模板page_param页码参数名 返回操作结果 7. 数据提取方法 7.1 get_text(elementNone, selectorNone, by“css”, timeoutNone) 功能获取元素的文本内容参数同find_element返回文本内容或 None 7.2 get_attribute(attribute, elementNone, selectorNone, by“css”, timeoutNone) 功能获取元素的属性值 参数 attribute属性名其他参数同find_element 返回属性值或 None 7.3 extract_data(template) 功能根据模板提取页面数据 参数 template数据提取模板格式为字典键为数据字段名值为选择器或提取函数 返回提取的数据 8. DevTools 方法 8.1 start_capturing_network() 功能开始捕获网络请求参数无 8.2 stop_capturing_network() 功能停止捕获网络请求参数无 8.3 get_captured_requests(filter_typeNone, url_patternNone) 功能获取捕获的网络请求 参数 filter_type请求类型过滤可选值xhr, fetch, script, image, stylesheet 等url_patternURL 模式过滤支持正则表达式 返回符合条件的请求列表 8.4 add_request_interceptor(pattern, handler_func) 功能添加请求拦截器 参数 patternURL 匹配模式handler_func处理函数接收请求对象可修改请求或返回自定义响应 返回拦截器 ID 9. 辅助方法 9.1 wait_for_element(selector, by“css”, timeoutNone, condition“visible”) 功能等待元素满足特定条件 参数 selector选择器字符串by选择器类型timeout超时时间condition等待条件可选值visible, present, clickable, invisible, not_present 返回元素对象或 None 9.2 execute_script(script, *args) 功能执行 JavaScript 代码 参数 scriptJavaScript 代码*args传递给 JavaScript 的参数 返回JavaScript 执行结果 9.3 set_delay(min_delay, max_delayNone) 功能设置操作之间的随机延迟 参数 min_delay最小延迟时间秒max_delay最大延迟时间秒如果为 None 则固定为 min_delay 返回无 9.4 take_screenshot(pathNone) 功能截取当前页面截图 参数 path保存路径如果为 None 则返回图像数据 返回如果 path 为 None返回图像二进制数据否则返回保存结果 WebScraper 类代码实现 package com.example.demo.utils;import com.google.gson.Gson; import com.google.gson.GsonBuilder; import io.github.bonigarcia.wdm.WebDriverManager; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.Proxy; 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.edge.EdgeDriver; import org.openqa.selenium.edge.EdgeOptions; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.firefox.FirefoxOptions; import org.openqa.selenium.firefox.FirefoxProfile; import org.openqa.selenium.remote.CapabilityType; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait;import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.time.Duration; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.*; import java.util.function.Function; import java.util.regex.Pattern; import java.util.stream.Collectors;public class WebScraper implements AutoCloseable {private static final MapString, By BY_MAP new HashMap();static {BY_MAP.put(css, By.cssSelector(*));BY_MAP.put(xpath, By.xpath(//*));BY_MAP.put(id, By.id(placeholder_id));BY_MAP.put(class, By.className(placeholder_class));BY_MAP.put(name, By.name(placeholder_name));BY_MAP.put(linktext, By.linkText(placeholder_linktext));BY_MAP.put(partiallinktext, By.partialLinkText(placeholder_partial));BY_MAP.put(tagname, By.tagName(div));}private WebDriver driver;private final String browserType;private final boolean headless;private final String userAgent;private final MapString, String proxyConfig;private final Duration timeout;private final boolean debug;private final String profileDirectory;private int currentPageNum 1;private double minDelay 0.5;private double maxDelay 1.5;private ListMapString, Object networkRequestsRaw new ArrayList();private final JavascriptExecutor jsExecutor;public WebScraper(String browserType, boolean headless, String userAgent,MapString, String proxyConfig, int timeoutSeconds, boolean debug, String profileDirectory) {this.browserType browserType.toLowerCase();this.headless headless;this.userAgent userAgent;this.proxyConfig proxyConfig;this.timeout Duration.ofSeconds(timeoutSeconds);this.debug debug;this.profileDirectory profileDirectory;setupDriver();this.jsExecutor (JavascriptExecutor) driver;}public WebScraper() {this(chrome, true, null, null, 30, false, null);}// 多个重载构造函数...private void printDebug(String message) {if (debug) {System.out.println([DEBUG] message);}}private void setupDriver() {// 浏览器驱动初始化逻辑...}private By getSeleniumBy(String byString, String selector) {// 选择器类型转换逻辑...}private void performDelay() {// 操作延迟逻辑...}// 浏览器控制方法实现...public boolean openUrl(String url) {// 打开URL逻辑...}Overridepublic void close() {// 关闭浏览器逻辑...}public void refresh() {// 刷新页面逻辑...}public void goBack() {// 返回上一页逻辑...}// 元素定位与交互方法实现...public WebElement findElement(String selector, String by, Duration customTimeout) {// 查找单个元素逻辑...}// 多个重载方法...public ListWebElement findElements(String selector, String by, Duration customTimeout) {// 查找多个元素逻辑...}// 多个重载方法...public boolean click(WebElement element, String selector, String by, Duration customTimeout) {// 点击元素逻辑...}// 多个重载方法...public boolean typeText(String text, WebElement element, String selector, String by, Duration customTimeout, boolean clearFirst) {// 输入文本逻辑...}// 多个重载方法...// 滚动方法实现...public boolean scroll(String direction, Integer amount, WebElement element, boolean smooth, double durationSeconds) {// 滚动逻辑...}// 多个重载方法...public boolean scrollToElement(WebElement element, String selector, String by, Duration customTimeout, String align) {// 滚动到元素逻辑...}// 多个重载方法...public boolean scrollToBottom(WebElement element, int steps, double delaySeconds) {// 滚动到底部逻辑...}// 多个重载方法...// 翻页方法实现...public boolean nextPage(String selector, String method, String urlTemplate, String pageParam, FunctionWebScraper, Boolean nextPageFunc) {// 翻页逻辑...}// 多个重载方法...public boolean hasNextPage(String selector, FunctionWebScraper, Boolean checkFunc) {// 检查下一页逻辑...}// 多个重载方法...public boolean setPage(int pageNum, String urlTemplate, String pageParam) {// 跳转到指定页逻辑...}// 数据提取方法实现...public String getText(WebElement element, String selector, String by, Duration customTimeout) {// 获取文本逻辑...}// 多个重载方法...public String getAttribute(String attribute, WebElement element, String selector, String by, Duration customTimeout) {// 获取属性逻辑...}// 多个重载方法...SuppressWarnings(unchecked)public MapString, Object extractData(MapString, Object template) {// 数据提取逻辑...}// DevTools方法实现...public void startCapturingNetwork() {// 开始捕获网络请求逻辑...}public void stopCapturingNetwork() {// 停止捕获网络请求逻辑...}SuppressWarnings(unchecked)public ListMapString, Object getCapturedRequests(String filterType, String urlPattern) {// 获取捕获的网络请求逻辑...}// 多个重载方法...public String addRequestInterceptor(String pattern, FunctionObject, Object handlerFunc) {// 添加请求拦截器逻辑...}// 辅助方法实现...public WebElement waitForElement(String selector, String by, Duration customTimeout, String condition) {// 等待元素逻辑...}// 多个重载方法...public Object executeScript(String script, Object... args) {// 执行JavaScript逻辑...}public void setDelay(double minDelaySeconds, double maxDelaySeconds) {// 设置延迟逻辑...}public boolean takeScreenshot(String path) {// 截图逻辑...}public byte[] takeScreenshot() {// 截图逻辑...}public WebDriver getDriver() {return driver;} }百度搜索使用案例 package com.example.demo.utils;import com.example.demo.utils.WebScraper; import org.openqa.selenium.WebElement;import java.util.Map; import java.util.concurrent.TimeUnit;public class BaiduSearchDemo {public static void main(String[] args) {String keyword 人工智能;int pageCount 5;try (WebScraper scraper new WebScraper(chrome, false, 30, true)) {performBaiduSearch(scraper, keyword, pageCount);} catch (Exception e) {System.err.println(百度搜索过程中发生错误: e.getMessage());e.printStackTrace();}}private static void performBaiduSearch(WebScraper scraper, String keyword, int pageCount) {System.out.println(正在打开百度首页...);if (!scraper.openUrl(https://www.baidu.com)) {System.err.println(打开百度首页失败);return;}System.out.println(正在输入搜索关键词: keyword);WebElement searchInput scraper.findElement(#kw, css);if (searchInput ! null) {scraper.typeText(keyword, searchInput);} else {System.err.println(未找到搜索输入框);return;}System.out.println(正在点击搜索按钮...);if (!scraper.click(#su, css)) {System.err.println(点击搜索按钮失败);return;}try {TimeUnit.SECONDS.sleep(2);} catch (InterruptedException e) {Thread.currentThread().interrupt();}for (int i 1; i pageCount; i) {System.out.println(正在处理第 i 页...);System.out.println(滚动到页面底部...);if (!scraper.scrollToBottom()) {System.err.println(滚动到页面底部失败);}extractCurrentPageInfo(scraper);if (i pageCount) {System.out.println(准备翻到下一页...);if (!goToNextPage(scraper)) {System.err.println(翻页失败停止操作);break;}try {TimeUnit.SECONDS.sleep(2);} catch (InterruptedException e) {Thread.currentThread().interrupt();}}}}private static void extractCurrentPageInfo(WebScraper scraper) {String pageTitle scraper.executeScript(return document.title).toString();String currentUrl scraper.executeScript(return window.location.href).toString();System.out.println(当前页面标题: pageTitle);System.out.println(当前页面URL: currentUrl);System.out.println(提取搜索结果标题:);int resultCount 0;for (WebElement titleElement : scraper.findElements(h3.t a, css)) {if (resultCount 5) {String title scraper.getText(titleElement);if (title ! null) {System.out.println( (resultCount 1) . title);}resultCount;} else {break;}}System.out.println(------------------------);}private static boolean goToNextPage(WebScraper scraper) {String nextPageSelector a.n;if (scraper.hasNextPage(nextPageSelector)) {return scraper.nextPage(nextPageSelector);} else {System.out.println(已到达最后一页没有更多内容);return false;}} }
http://www.dnsts.com.cn/news/198703.html

相关文章:

  • 浙江省通信管理局 网站备案 管理部门wordpress微信分享图
  • 南京做网站公司地点公众号推送怎么制作
  • 厦门网站模板响应式网站制作教程
  • 绿色食品网站开发步骤平台网站开发公司
  • 网站建设就找奇思网络游戏定制公司
  • 网络营销 网站北京大型商场
  • 辽宁高速公路建设局网站wordpress做管理系统
  • 电商网站简单html模板下载系统开发立项报告
  • 四川建设厅网站招聘关于电子商务网站建设的现状
  • 自己怎样做免费网站网站公司做网站修改会收费吗
  • 博物馆网站制作做音响网站
  • 梁山县城市建设局网站东莞 营销网站制作
  • 重庆建设行业网站网站优化主要优化哪些地方
  • 网站设计公司北京网络营销是什么的思维导图
  • WordPress站内链接设置网站制作创业
  • 客户管理系统网站模板下载网站备案取消流程
  • 汉中专业网站建设公司动漫设计学校哪里好
  • 一般拍卖会在什么网站做建设股份有限公司
  • 网站与系统开发wordpress横向导航
  • 网站的seo优化报告腾讯学生服务器可以做网站吗
  • 简历免费在线制作网站万网域名解析
  • 织梦网站排版能调整吗公司外贸网站怎么做
  • 营销型网站如何制作滨海新区做网站
  • 腾度网站建设专家兼职做网站安全么
  • 企业网站建设策划书自建站怎么搭建
  • 巨腾外贸网站建设网站编辑怎么做
  • 凡科网站为什么免费做网站小学网站建设
  • 一个网站建设多少钱?微信app网站建设
  • 铁岭网站建设公司装饰工程公司起名字大全免费
  • 如何申请建设网站网站开发主要内容和要求