当前位置:首页 > Software > Python > 正文内容

Python基于Searx进行信息搜索

chanra1n1年前 (2025-01-27)Python2208

Python版本:3.7

代码如下:

import requests
from bs4 import BeautifulSoup
from concurrent.futures import ThreadPoolExecutor, as_completed
import logging
import time
from typing import List, Dict

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s [%(levelname)s] %(message)s',
    handlers=[
        logging.FileHandler('searx_search.log'),
        logging.StreamHandler()
    ]
)

# Searx实例列表URL
SEARX_INSTANCES_URL = 'https://data.myfpga.cn/searx.txt'

# 最大并发数
MAX_CONCURRENT = 3

class SearxSearcher:
    def __init__(self):
        self.session = requests.Session()
        self.session.headers.update({'User-Agent': 'Mozilla/5.0'})
        self.search_instances = self._load_instances()
        self.executor = ThreadPoolExecutor(max_workers=MAX_CONCURRENT)

    def _load_instances(self) -> List[str]:
        """从URL加载Searx实例列表"""
        try:
            response = self.session.get(SEARX_INSTANCES_URL, timeout=10)
            return [i.strip() for i in response.text.split('\n') if i.strip()][:10]
        except Exception as e:
            logging.error(f"实例加载失败: {str(e)}")
            return ["https://search.us.projectsegfau.lt"]

    def search(self, query: str, pages: int = 10) -> List[Dict]:
        """搜索并解析结果"""
        futures = {
            self.executor.submit(self._search_instance, instance, query, pages): instance
            for instance in self.search_instances[:MAX_CONCURRENT]
        }
        results = []
        for future in as_completed(futures):
            instance_results = future.result()  # 避免使用海象运算符
            if instance_results:
                results.extend(instance_results)
        return results[:pages * 10]  # 返回前10页的结果

    def _search_instance(self, instance: str, query: str, pages: int) -> List[Dict]:
        """在单个Searx实例上搜索并解析结果"""
        results = []
        for page in range(1, pages + 1):
            try:
                response = self.session.get(
                    f"{instance}/search",
                    params={
                        'q': query,
                        'category_general': 1,
                        'language': 'auto',
                        'time_range': '',
                        'safesearch': 0,
                        'theme': 'simple',
                        'pageno': page
                    },
                    timeout=15
                )
                if not response.ok:
                    logging.warning(f"请求失败: {instance} 第 {page} 页")
                    break

                soup = BeautifulSoup(response.text, 'html.parser')
                main_div = soup.find('div', id='results')
                if not main_div:
                    logging.warning(f"未找到结果: {instance} 第 {page} 页")
                    break

                for article in main_div.find_all('article', class_='result'):
                    title = article.find('h3').get_text(strip=True) if article.find('h3') else '无标题'
                    url = article.find('a', class_='url_header')['href'] if article.find('a', class_='url_header') else '无URL'
                    content = article.find('p', class_='content').get_text(strip=True) if article.find('p', class_='content') else '无内容'
                    results.append({
                        'title': title,
                        'url': url,
                        'content': content
                    })

                time.sleep(0.5)  # 防止请求过快
            except Exception as e:
                logging.error(f"解析失败: {instance} 第 {page} 页 - {str(e)}")
                break
        return results

if __name__ == "__main__":
    searcher = SearxSearcher()
    query = "myfpga.cn"
    results = searcher.search(query, pages=10)
    
    for i, result in enumerate(results, 1):
        print(f"结果 {i}:")
        print(f"标题: {result['title']}")
        print(f"URL: {result['url']}")
        print(f"内容: {result['content']}")
        print("-" * 80)


扫描二维码推送至手机访问。

版权声明:本文由我的FPGA发布,如需转载请注明出处。

本文链接:https://myfpga.cn/index.php/post/434.html

分享给朋友:

“Python基于Searx进行信息搜索” 的相关文章

2.Python中的基本运算

2.Python中的基本运算

我们打开Python,请你尝试输入如下算式并尝试理解有什么为什么是这样的?1+1 1+1.0 1-2 2-3.5 1*1 1*1.1 1/2 2/1 2/3 3/2 3//2 3/1.0 5/2.5我们不难得到如下结果2 2.0 -1 -1.5 1 1.1 0.5...

搜索字符串

搜索字符串

常用搜索字符串中子串的方法str.count(substring)      返回str中substring子串出现的无覆盖的次数str.find(s1)                    返回s1在这个字符串的最低下标,如果字符串中不存在s1,则返回-1str.rfind(s1)       ...

random库

random库

random()            生成一个[0.0,1.0)之间的随机小数randint(a,b)     生成一个[a,b]之间的整数uniform(a,b)     生成一个[a,b]之间的随机小数对random库的引用方法与math库一样,采用下面两种方式实现:import random...

体温打卡python 可通过账户密码获取对应ID号

体温打卡python 可通过账户密码获取对应ID号

仅用于学习和测试,请勿自动填报或者干任何违法的事情import datetime import hashlib import random from urllib.parse import quote import req...

Python自动清理错误图片,深度学习训练数据集准备

Python自动清理错误图片,深度学习训练数据集准备

使用python运行from PIL import Image from pathlib import Path import os   path = r'.'  ...

(原创)使用Python自动对子文件夹中的图片文件进行重命名

(原创)使用Python自动对子文件夹中的图片文件进行重命名

为了解决Python深度学习的时候,经常遇到的文件名问题import os # 获取指定目录下的所有子文件夹 def get_subfolders(path):     subfolders = []...