2024-08-11



import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
 
public class SeleniumExample {
    public static void main(String[] args) {
        // 设置webdriver路径
        System.setProperty("webdriver.chrome.driver", "C:\\path\\to\\chromedriver.exe");
 
        // 初始化一个新的ChromeDriver实例
        WebDriver driver = new ChromeDriver();
 
        // 使用Selenium打开网页
        driver.get("http://www.example.com");
 
        // 关闭浏览器
        driver.quit();
    }
}

这段代码演示了如何使用Selenium WebDriver和ChromeDriver在Java中打开一个浏览器窗口,导航到指定的网页,并在最后关闭浏览器。在实际应用中,你可以通过Selenium的WebElement定位页面元素,模拟用户的行为,如点击、填写表单等,进行更复杂的自动化测试和数据抓取工作。

2024-08-11



import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
 
public class SimpleWebCrawler {
 
    public static void main(String[] args) throws Exception {
        URL url = new URL("http://example.com");
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
 
        int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String inputLine;
            StringBuilder content = new StringBuilder();
 
            while ((inputLine = in.readLine()) != null) {
                content.append(inputLine);
                content.append("\n");
            }
 
            in.close();
            connection.disconnect();
 
            // 对获取的内容进行处理
            String webPageContent = content.toString();
            // 例如,可以打印出网页内容
            System.out.println(webPageContent);
        } else {
            System.out.println("GET request not worked");
        }
    }
}

这段代码展示了如何使用Java进行简单的网络爬取。它创建了一个指向http://example.comURL对象,然后建立了一个HTTP连接,发送了一个GET请求。如果响应码是200(HTTP\_OK),它将读取服务器响应的内容,并将其存储到一个字符串中,然后关闭连接并打印出网页内容。如果响应码不是200,它将输出一个错误消息。这个例子是一个基本的网络爬虫示例,实际应用中可能需要更复杂的处理,比如解析HTML、处理重定向、处理多线程/异步下载等。

2024-08-11

以下是一个简单的Python爬虫示例,使用requests库和BeautifulSoup进行网页爬取,爬取Google图片搜索中关于蛇的照片。

首先,你需要安装必要的库(如果尚未安装的话):




pip install requests
pip install beautifulsoup4

然后,你可以使用以下代码来实现爬虫:




import requests
from bs4 import BeautifulSoup
import os
 
# 目标网址的前缀
base_url = "https://www.google.com/search?tbm=isch&q=snake"
 
# 图片保存路径
save_path = 'snake_images/'
if not os.path.exists(save_path):
    os.makedirs(save_path)
 
# 用户代理,以防被识别并禁止爬取
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}
 
def download_image(image_url, file_path):
    response = requests.get(image_url, headers=headers)
    with open(file_path, 'wb') as f:
        f.write(response.content)
        print(f"Image saved: {file_path}")
 
def get_image_urls(url):
    response = requests.get(url, headers=headers)
    soup = BeautifulSoup(response.text, 'html.parser')
    image_urls = [img['src'] for img in soup.find_all('img', class_='Q4LuWd')]
    return image_urls
 
def main():
    image_urls = get_image_urls(base_url)
    for i, image_url in enumerate(image_urls):
        file_path = os.path.join(save_path, f"snake_{i}.jpg")
        download_image(image_url, file_path)
 
if __name__ == '__main__':
    main()

请注意,这个爬虫依赖于Google图片搜索的HTML结构,该结构可能会随着时间变化而变化,因此可能需要进行适当的调整。此外,过度使用此爬虫可能会触发Google的反爬虫机制,导致被封禁。使用爬虫时请遵守相关法律法规,并尊重网站的robots.txt规则。

2024-08-11

Java实现爬虫功能通常使用HttpClient来发送HTTP请求,以及Jsoup来解析HTML页面。以下是一个简单的Java爬虫示例,用于抓取一个网页的标题:




import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
 
public class SimpleCrawler {
 
    public static void main(String[] args) {
        HttpClient client = HttpClients.createDefault();
        HttpGet request = new HttpGet("http://example.com"); // 替换为你想爬取的网址
 
        try {
            HttpResponse response = client.execute(request);
            String html = EntityUtils.toString(response.getEntity());
 
            Document doc = Jsoup.parse(html);
            String title = doc.title();
 
            System.out.println("Title of the page: " + title);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

确保在执行此代码前,你的项目中已经加入了HttpClientJsoup的依赖。

Maven依赖如下:




<dependencies>
    <!-- Jsoup -->
    <dependency>
        <groupId>org.jsoup</groupId>
        <artifactId>jsoup</artifactId>
        <version>1.13.1</version>
    </dependency>
    <!-- HttpClient -->
    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.5.13</version>
    </dependency>
</dependencies>

这个例子只是一个简单的开始。实际的爬虫可能需要处理更复杂的情况,比如多线程下载、处理JavaScript动态内容、处理cookie和session、处理网页重定向、爬取动态加载的内容等。

2024-08-11



const Crawler = require("crawler");
 
// 创建爬虫实例
const crawler = new Crawler({
    maxConnections: 10,
    callback: function (error, res, done) {
        if (error) {
            console.error(error);
        } else {
            const $ = res.$;
 
            // 假设我们只关心<h2>标签内的文章标题和链接
            $('h2.title a').each(function() {
                const title = $(this).text();
                const link = $(this).attr('href');
                console.log('标题: ' + title + ' - 链接: ' + link);
            });
        }
        done();
    }
});
 
// 定义爬取的URL和选择器
const crawlConfig = {
    uri: 'http://example.com/blog',
    jQuery: 'h2.title a@href',
    callback: function (err, res) {
        if (err) {
            console.error(err);
        } else {
            res.forEach(link => {
                console.log('爬取到的文章链接: ' + link);
                // 将文章链接加入爬虫队列
                crawler.queue({
                    uri: link,
                    jQuery: 'h2.title'
                });
            });
        }
    }
};
 
// 开始爬取
crawler.queue(crawlConfig);

这段代码使用了node-crawler库来爬取指定的博客首页,并获取文章链接,然后爬取每篇文章的标题。这个例子展示了如何使用node-crawler库的基本用法,并且如何通过回调函数处理爬取的数据。

2024-08-11

以下是一个简化的Python爬虫程序示例,用于从Fofa中批量获取CVE漏洞相关的信息。




import requests
import csv
 
# Fofa API 相关配置
FOFA_API_URL = "https://fofa.info/api/v1/search/all"
FOFA_EMAIL = "your_email@example.com"
FOFA_KEY = "your_fofa_api_key"
 
# CVE 列表,这里只列举了几个示例
cve_list = ["CVE-2017-11499", "CVE-2018-1000002", "CVE-2018-1000003"]
 
# 构建查询
queries = [f'title="{cve}"' for cve in cve_list]
 
# 结果文件
result_file = "cve_results.csv"
 
# 发送请求
def send_request(query):
    payload = {
        "email": FOFA_EMAIL,
        "key": FOFA_KEY,
        "query": query
    }
    response = requests.get(FOFA_API_URL, params=payload)
    return response.json()
 
# 保存结果
def save_results(results, file_name):
    with open(file_name, 'w', newline='', encoding='utf-8') as csvfile:
        writer = csv.writer(csvfile)
        writer.writerow(['CVE', 'Hostname', 'IP'])
        for result in results:
            hostname = result.get('hostname')
            ip = result.get('ip')
            for cve in cve_list:
                writer.writerow([cve, hostname, ip])
 
# 主函数
def main():
    results = []
    for query in queries:
        response = send_request(query)
        results.extend(response.get('results'))
    save_results(results, result_file)
 
if __name__ == "__main__":
    main()

这个示例程序首先定义了Fofa API 的URL和认证信息,然后构建了一个CVE列表。通过循环构建查询,并发送请求到Fofa API获取数据,最后将结果保存到CSV文件中。

注意:实际使用时需要替换FOFA_EMAILFOFA_KEY为您的有效凭证,并确保您有足够的查询配额来执行这些查询。

2024-08-11

memory_profiler是一个Python库,用于监测Python程序的内存使用情况。它通过装饰器的方式,可以在特定的函数或者代码块执行前后,记录内存的使用情况。

首先,你需要安装memory_profiler库:




pip install memory_profiler

然后,你可以使用@profile装饰器来监测函数的内存使用情况:




from memory_profiler import profile
 
@profile
def my_func():
    a = [1] * (10 ** 6)
    b = [2] * (2 * 10 ** 7)
    del b
    return a
 
if __name__ == "__main__":
    my_func()

运行这段代码时,memory_profiler会记录my_func函数的内存使用情况,并在终端打印出结果。

如果你想要在不修改原有代码的情况下,使用memory_profiler来分析脚本,可以使用命令行工具mprof




mprof run your_script.py

执行完毕后,mprof会在当前目录生成一个your_script.py.memory.png的内存使用图。

2024-08-11

在Python中,你可以使用多种方法来获取文件的大小。以下是四种主要的方法:

  1. 使用os模块的os.path.getsize()函数
  2. 使用os模块的os.stat()函数
  3. 使用pathlib模块的Path.stat()方法
  4. 使用open函数打开文件,然后使用file.seek和file.tell方法

解决方案和实例代码如下:

  1. 使用os模块的os.path.getsize()函数



import os
 
def get_file_size(file_path):
    return os.path.getsize(file_path)
 
file_path = 'test.txt'
print(get_file_size(file_path))
  1. 使用os模块的os.stat()函数



import os
 
def get_file_size(file_path):
    return os.stat(file_path).st_size
 
file_path = 'test.txt'
print(get_file_size(file_path))
  1. 使用pathlib模块的Path.stat()方法



from pathlib import Path
 
def get_file_size(file_path):
    return Path(file_path).stat().st_size
 
file_path = 'test.txt'
print(get_file_size(file_path))
  1. 使用open函数打开文件,然后使用file.seek和file.tell方法



def get_file_size(file_path):
    with open(file_path, 'rb') as file:
        file.seek(0, 2)  # 移动到文件末尾
        size = file.tell()  # 获取当前位置
    return size
 
file_path = 'test.txt'
print(get_file_size(file_path))

以上四种方法都可以用来获取文件的大小,你可以根据实际需求选择合适的方法。

2024-08-11

这个问题通常是由以下几个原因导致的:

  1. 环境问题:你可能在一个虚拟环境中安装了库,但是在另一个环境中运行代码。
  2. 路径问题:Python解释器可能没有正确地指向库所在的路径。
  3. 文件名冲突:如果你安装的库或者运行的脚本文件与系统文件名冲突,也会导致找不到模块。
  4. 安装不完全:库可能没有正确安装,或者安装过程中出现了错误。
  5. 缓存问题:Python的包管理器(pip)可能有缓存,需要清理。

解决方法:

  1. 检查环境:确保你在正确的虚拟环境中安装和运行代码。
  2. 检查路径:使用sys.path查看Python解释器的搜索路径,确保库文件所在目录在搜索路径中。
  3. 修改文件名:如果文件名冲突,尝试重命名你的脚本或库。
  4. 重新安装库:尝试重新安装库,使用pip uninstall <库名>pip install <库名>命令。
  5. 清理缓存:清理pip缓存,可以使用pip cache purge命令。

在解决问题时,请依次排查这些可能性,直到找到问题的原因并解决它。

2024-08-11



import onnxruntime
 
# 创建ONNX运行时会话
# 第一个参数是模型路径,第二个参数是软件设置,例如:会话选项
# 这里使用默认设置
session = onnxruntime.InferenceSession("path_to_your_model.onnx")
 
# 输入数据准备
# 假设模型期望的输入名称是 'input_name'
input_name = session.get_inputs()[0].name
input_data = ...  # 你的输入数据,应该是一个numpy数组
 
# 运行模型进行推断
outputs = session.run([], {input_name: input_name})
 
# 输出结果
print(outputs)

这段代码演示了如何使用ONNX Runtime Python API加载一个ONNX模型并对输入数据进行推断。需要替换"path_to_your_model.onnx"为你的模型文件路径,并且准备相应的输入数据。输出将是模型的预测结果。