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

Python基于Searx进行信息搜索

chanra1n1年前 (2025-01-27)Python1716

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://world.myfpga.cn/index.php/post/434.html

分享给朋友:

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

random库

random库

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

顺序查找

顺序查找

如果需要查找某个特定值的位置(以便能够替换或删除它),可以直接使用index方法。searchedValue=100 #values是之前定义好的一个列表 if searchedValue in walues:     pos=values.index(searchedValue)     ...

体温打卡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对任意网站图片进行爬取,仅用于学习

import os import time import argparse import requests import re import io from urllib.parse import ...

(原创)使用Python递归获取网页内的所有URL,并进行清洗

(原创)使用Python递归获取网页内的所有URL,并进行清洗

import argparse import time from urllib.parse import urljoin, urlparse from selenium import webdriver...