frontiers_search.py

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Frontiers 论文搜索脚本
"""

import argparse
import requests
from bs4 import BeautifulSoup

def search_frontiers_papers(keyword, journal=None, max_results=10):
    """
    搜索 Frontiers 论文
    
    Args:
        keyword: 搜索关键词
        journal: 期刊名称(可选)
        max_results: 最大结果数
        
    Returns:
        论文列表
    """
    # 构建搜索 URL
    base_url = "https://www.frontiersin.org/search"
    params = {
        "query": keyword,
        "pageSize": max_results
    }
    
    if journal:
        params["journal"] = journal
    
    try:
        response = requests.get(base_url, params=params)
        response.raise_for_status()
        
        # 解析 HTML
        soup = BeautifulSoup(response.text, 'html.parser')
        
        # 查找论文条目
        papers = []
        paper_items = soup.find_all('div', class_='article-item')
        
        for item in paper_items[:max_results]:
            # 提取论文标题
            title_elem = item.find('h2', class_='title')
            title = title_elem.text.strip() if title_elem else "No title"
            
            # 提取论文链接
            link_elem = item.find('a', href=True)
            link = f"https://www.frontiersin.org{link_elem['href']}" if link_elem else ""
            
            # 提取作者
            author_elem = item.find('div', class_='authors')
            authors = author_elem.text.strip() if author_elem else "No authors"
            
            # 提取期刊和出版日期
            info_elem = item.find('div', class_='pub-info')
            pub_info = info_elem.text.strip() if info_elem else "No info"
            
            papers.append({
                "title": title,
                "link": link,
                "authors": authors,
                "pub_info": pub_info
            })
        
        return papers
        
    except requests.exceptions.RequestException as e:
        print(f"搜索失败: {e}")
        return []

def main():
    parser = argparse.ArgumentParser(description="搜索 Frontiers 期刊论文")
    parser.add_argument("keyword", help="搜索关键词")
    parser.add_argument("--journal", help="特定期刊名称(可选)")
    parser.add_argument("--max-results", type=int, default=10, help="最大结果数")
    
    args = parser.parse_args()
    
    print(f"搜索 Frontiers 论文: {args.keyword}")
    if args.journal:
        print(f"期刊: {args.journal}")
    
    papers = search_frontiers_papers(args.keyword, args.journal, args.max_results)
    
    if papers:
        print(f"\n找到 {len(papers)} 篇论文:\n")
        for i, paper in enumerate(papers, 1):
            print(f"{i}. {paper['title']}")
            print(f"   作者: {paper['authors']}")
            print(f"   信息: {paper['pub_info']}")
            print(f"   链接: {paper['link']}")
            print()
    else:
        print("未找到匹配的论文")

if __name__ == "__main__":
    main()