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

arxiv论文信息爬取与论文pdf下载

文章目录

  • 一,前言
  • 二,爬虫描述
  • 三,使用步骤与代码
    • 3.1,爬取论文信息
  • 3.2,论文信息生成器
  • 3.3,批量爬取论文PDF

一,前言

在科研的过程中,文献阅读是不可或缺的一环。通过阅读相关领域的论文,研究人员能够及时了解最新的研究成果,掌握前沿技术和理论,同时避免重复劳动,提升研究效率。尤其是在复杂的科研项目中,海量的文献往往是支撑创新的基础。因此,如何高效获取和整理相关领域的文献,成为科研工作中的一个关键问题。

在实际科研中,尤其是针对某一特定领域的深入研究时,研究人员往往需要阅读大量的论文,这些论文不仅来源广泛,而且更新速度迅速。随着开放获取(Open Access)学术资源的普及,像 arXiv 这样的数据库为学者提供了丰富的免费科研文献。然而,面对海量的文献,手动筛选和下载论文显得尤为繁琐且效率低下。因此,批量下载相关文献成为了科研人员高效工作的必要手段。

为了提高科研文献获取的效率,构建一个自动化的论文爬取程序显得尤为重要。通过开发 arXiv 论文爬取程序,研究人员可以快速、准确地抓取和下载感兴趣领域的文献,节省大量时间用于深入分析和研究。爬取程序能够自动处理搜索、筛选、下载等流程,不仅能够提高工作效率,还能避免人工操作中的错误和遗漏,确保文献资料的完整性和准确性。

总之,科研文献的批量下载是提高研究效率的关键步骤,而 arXiv 论文爬取程序正是实现这一目标的有效工具。它为科研人员提供了更为便捷的文献获取途径,从而加速了科研创新的步伐。

二,爬虫描述

该爬虫程序的主要功能是根据用户在 arXiv 网站上搜索关键字并获取相应的搜索结果网址,用户只需复制该网址,爬虫程序将自动从网页中提取每篇论文的相关信息,包括标题、作者、摘要、提交日期以及 PDF 链接。爬虫程序会根据这些信息组合出每篇论文的 PDF 下载链接,并自动批量下载所有符合条件的论文 PDF 文件。该程序通过逐页爬取并提取数据,大大简化了文献获取的过程,提高了科研人员的工作效率。

三,使用步骤与代码

3.1,爬取论文信息

这段代码的功能是根据用户提供的 arXiv 搜索结果页面链接,自动爬取页面中的每篇论文的详细信息。爬取的内容包括:

标题(Title):论文的标题。
作者(Authors):论文的所有作者。
摘要(Abstract):论文的简短摘要。
提交日期(Submission Date):论文提交到 arXiv 的日期。
PDF 链接(PDF Link):论文的 PDF 下载链接。
代码通过解析网页内容,提取出每篇论文的相关信息,并将这些信息存储为可供进一步使用的格式。用户只需提供搜索结果页面的 URL,程序即可自动化地爬取该页面上的所有论文数据。
在这里插入图片描述
在使用下面代码时,只需要修改你想爬取主题的url,每个页面文章数,存储路径即可。下面是具体代码。

from lxml import html
import requests
import re
import math
import csv
from bs4 import BeautifulSoup
import time


def get_total_results(url):
    """获取总结果数"""
    response = requests.get(url)
    tree = html.fromstring(response.content)
    result_string = ''.join(tree.xpath('//*[@id="main-container"]/div[1]/div[1]/h1/text()')).strip()
    match = re.search(r'of ([\d,]+) results', result_string)
    if match:
        total_results = int(match.group(1).replace(',', ''))
        return total_results
    else:
        print("没有找到匹配的数字。")
        return 0


def get_paper_info(url):
    """根据URL爬取一页的论文信息"""
    response = requests.get(url)
    soup = BeautifulSoup(response.content, 'html.parser')
    papers = []

    for article in soup.find_all('li', class_='arxiv-result'):
        title = article.find('p', class_='title').text.strip()
        authors_text = article.find('p', class_='authors').text.replace('Authors:', '').strip()
        authors = [author.strip() for author in authors_text.split(',')]
        abstract = article.find('span', class_='abstract-full').text.strip()
        submitted = article.find('p', class_='is-size-7').text.strip()
        submission_date = submitted.split(';')[0].replace('Submitted', '').strip()
        pdf_link_element = article.find('a', text='pdf')
        if pdf_link_element:
            pdf_link = pdf_link_element['href']
        else:
            pdf_link = 'No PDF link found'

        papers.append({'title': title, 'authors': authors, 'abstract': abstract, 'submission_date': submission_date,
                       'pdf_link': pdf_link})

    return papers


def save_to_csv(papers, filename):
    """将所有爬取的论文信息保存到CSV文件中"""
    with open(filename, 'w', newline='', encoding='utf-8') as csvfile:
        fieldnames = ['title', 'authors', 'abstract', 'submission_date', 'pdf_link']
        writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
        writer.writeheader()
        for paper in papers:
            writer.writerow(paper)


# 主程序
# 修改这里的链接
base_url ="https://arxiv.org/search/?query=tidal+wave&searchtype=abstract&abstracts=show&order=-announced_date_first&size=50"
total_results = get_total_results(base_url + "&start=0")
pages = math.ceil(total_results / 50)
all_papers = []

for page in range(pages):
    start = page * 50
    print(f"Crawling page {page + 1}/{pages}, start={start}")
    page_url = base_url + f"&start={start}"
    all_papers.extend(get_paper_info(page_url))
    time.sleep(3)  # 等待三秒以避免对服务器造成过大压力

# 保存到CSV
save_to_csv(all_papers, 'paper_result.csv')
print(f"完成!总共爬取到 {len(all_papers)} 条数据,已保存到 paper_result.csv 文件中。")

3.2,论文信息生成器

这段代码的功能是读取包含论文信息的 CSV 文件,并从中提取所需的字段,将这些字段拼接成适合爬虫程序使用的格式,以便后续用于批量爬取和下载论文。具体来说,代码会从 CSV 文件中读取每篇论文的 标题、提交日期 和 PDF 链接,然后将这些信息组合成爬虫能够解析和处理的markdown格式,从而实现自动化文献下载的功能。这些markdown字段被转换为可供爬虫程序进一步使用的输入,确保爬虫能够准确抓取和下载对应的论文文件。
生成的内容格式如下:

+ Could TDE outflows produce the PeV neutrino events?, arxiv 2022, [[paper]](https://arxiv.org/pdf/2112.01748).
+ Constraints on the fermionic dark matter from observations of neutron stars, arxiv 2021, [[paper]](https://arxiv.org/pdf/2111.13289).
+ Dark Matter-admixed Rotating White Dwarfs as Peculiar Compact Objects, arxiv 2022, [[paper]](https://arxiv.org/pdf/2111.12894).
+ Longitudinally asymmetric stratospheric oscillation on a tidally locked exoplanet, arxiv 2021, [[paper]](https://arxiv.org/pdf/2111.11281).
+ Understanding binary neutron star collisions with hypermodels, arxiv 2022, [[paper]](https://arxiv.org/pdf/2111.09214).
+ Analytic models of the spectral properties of gravitational waves from neutron star merger remnants, arxiv 2022, [[paper]](https://arxiv.org/pdf/2111.08353).
+ Neutron stars in massive scalar-Gauss-Bonnet gravity: Spherical structure and time-independent perturbations, arxiv 2021, [[paper]](https://arxiv.org/pdf/2111.06561).
+ The Second Love Number of Dark Compact Planets and Neutron Stars with Dark Matter, arxiv 2022, [[paper]](https://arxiv.org/pdf/2111.06197).
+ Gravitational waves from tidal disruption events: an open and comprehensive catalogue, arxiv 2021, [[paper]](https://arxiv.org/pdf/2111.05145).

使用下面的代码可以不用修改任何地方。

import csv
import re

def read_csv(file_name):
    papers = []
    with open(file_name, newline='', encoding='utf-8') as csvfile:
        reader = csv.DictReader(csvfile)
        for row in reader:
            title = row['title']
            submission = row['submission_date']
            pdf_link = row['pdf_link']
            papers.append({'title': title, 'submission_date': submission, 'pdf_link': pdf_link})
    return papers

def extract_year(submission):

    match = re.search(r'\d{4}', submission)
    if match:
        return match.group(0)
    else:
        return 'Unknown'

def format_paper(paper):
    title = paper['title']

    year = extract_year(paper['submission_date'])
    pdf_link = paper['pdf_link']
    return f"+ {title}, arxiv {year}, [[paper]]({pdf_link})."

def generate_paper_list(file_name):
    papers = read_csv(file_name)
    formatted_papers = [format_paper(paper) for paper in papers]
    return formatted_papers

def save_to_file(papers, output_file):
    with open(output_file, 'w', encoding='utf-8') as f:
        for paper in papers:
            f.write(paper + '\n')

# 主程序
input_file = 'paper_result.csv'  # 输入 CSV 文件
output_file = 'formatted_papers.txt'  # 输出格式化后的文本文件
papers = generate_paper_list(input_file)
save_to_file(papers, output_file)

print(f"已保存 {len(papers)} 条格式化的论文信息到 {output_file}.")

3.3,批量爬取论文PDF

这段代码的功能是根据从前面提供的字段信息(如标题、提交日期和 PDF 链接)批量从 arXiv 网站下载论文的 PDF 文件。具体步骤如下:

读取markdown:程序首先从提供的 CSV 文件中读取每篇论文的标题、提交日期和 PDF 链接。
解析 PDF 链接:通过从 CSV 中获取的 PDF 链接,程序构建每篇论文的完整下载链接。
批量下载:程序根据这些链接自动访问 arXiv,下载对应论文的 PDF 文件。
文件保存:下载的 PDF 文件会被保存到本地,文件名通常基于论文的标题或其他唯一标识符生成,以便后续查找和使用。
通过该功能,用户可以快速批量下载特定领域的论文,避免了手动逐篇下载的繁琐过程,大大提高了文献获取的效率。
下面代码中只需要修改markdown部分。

import os
import requests
import re

# 你的Markdown内容
markdown_content = '''

<div align="center">
    <h1>Awesome LLM4RS Papers</h1>
    <a href="https://awesome.re">
        <img src="https://awesome.re/badge.svg"/>
    </a>
</div>

This is a paper list about Large Language Model-enhanced Recommender System. It also contains some related works.

**Keywords**: *recommendation system, large language models*

Welcome to open an issue or make a pull request!

## Tsunami
+ Feasibility of Dark Matter in Neutron Stars: A Quantitative Analysis, arxiv 2025, [[paper]](https://arxiv.org/pdf/2502.16629).
+ Hyper-neutron stars from an ab initio calculation, arxiv 2025, [[paper]](https://arxiv.org/pdf/2502.14435).
+ Segregation in Nuclear Stellar Clusters: Rates and Mass Distributions of TDEs, QPEs, Plunges, and EMRIs, arxiv 2025, [[paper]](https://arxiv.org/pdf/2502.13209).
+ Gravitational Effects of a Small Primordial Black Hole Passing Through the Human Body, arxiv 2025, [[paper]](https://arxiv.org/pdf/2502.09734).
+ Impact of mass transfer on the orbital evolution of a white dwarf close to an intermediate-mass black hole, arxiv 2025, [[paper]](https://arxiv.org/pdf/2502.06160).
+ Post-Newtonian orbital evolution and gravitational wave forms of inspiralling compact binaries with mass transfer and spin corrections, arxiv 2025, [[paper]](No PDF link found).
+ Observational and Theoretical Constraints on First-Order Phase Transitions in Neutron Stars, arxiv 2025, [[paper]](https://arxiv.org/pdf/2502.05519).
+ The Equation of State of Neutron Stars: Theoretical Models, Observational Constraints, and Future Perspectives, arxiv 2025, [[paper]](https://arxiv.org/pdf/2502.05513).
+ Probing Spin-Orbit Resonances with the Binary Black Hole Population, arxiv 2025, [[paper]](https://arxiv.org/pdf/2502.04278).
+ Fundamental Oscillation Modes in Neutron Stars with Hyperons and Delta Baryons, arxiv 2025, [[paper]](https://arxiv.org/pdf/2502.04264).
+ pyEFPE: An improved post-Newtonian waveform model for inspiralling precessing-eccentric compact binaries, arxiv 2025, [[paper]](https://arxiv.org/pdf/2502.03929).
+ Optimizing Bayesian model selection for equation of state of cold neutron stars, arxiv 2025, [[paper]](https://arxiv.org/pdf/2502.03831).
+ Cosmic Calipers: Precise and Accurate Neutron Star Radius Measurements with Next-Generation Gravitational Wave Detectors, arxiv 2025, [[paper]](https://arxiv.org/pdf/2502.03463).



'''

# 目标文件夹
output_dir = "文件夹目录"

# 提取Markdown中的链接信息并按照大类组织
paper_data = []

# 匹配模式以提取论文和代码链接
paper_pattern = r'\[\[paper\]\]\((.*?)\)'
code_pattern = r'\[\[code\]\]\((.*?)\)'
section_pattern = r'##\s(.+)'  # 匹配大类标题

# 当前大类
current_section = None

# 用于提取文章标题的正则表达式
title_pattern = r'^\+\s(.+?),\s'

# 按行解析Markdown内容
for line in markdown_content.split('\n'):
    # 检查是否进入新大类
    section_match = re.match(section_pattern, line)
    if section_match:
        current_section = section_match.group(1).strip()

    paper_link = re.search(paper_pattern, line)
    code_link = re.search(code_pattern, line)
    title_match = re.search(title_pattern, line)

    if title_match and paper_link:
        title = title_match.group(1).replace('/', '-').replace(':', '-').strip()  # 去除特殊字符
        paper_data.append({
            'section': current_section,  # 记录当前大类
            'title': title,
            'paper_link': paper_link.group(1),
            'code_link': code_link.group(1) if code_link else None
        })

# 确保输出目录存在
if not os.path.exists(output_dir):
    os.makedirs(output_dir)

# 打印提取出的链接
print("提取出的论文和代码链接:")
for paper in paper_data:
    print(f"大类: {paper['section']}")
    print(f"标题: {paper['title']}")
    print(f"论文链接: {paper['paper_link']}")
    if paper['code_link']:
        print(f"代码链接: {paper['code_link']}")
    else:
        print(f"代码链接: 无")
    print("-" * 80)


# 下载文章和代码到相应的文件夹
def download_file(url, folder, filename):
    try:
        print(f"开始下载: {url}{folder}/{filename}")  # 增加调试信息
        response = requests.get(url)
        print(f"HTTP状态码: {response.status_code}")  # 打印HTTP状态码
        response.raise_for_status()
        filepath = os.path.join(folder, filename)
        with open(filepath, 'wb') as f:
            f.write(response.content)
        print(f"成功下载: {filename}")
    except requests.exceptions.RequestException as e:
        print(f"下载失败: {url}, 错误: {e}")
    except IOError as e:
        print(f"文件保存失败: {filename}, 错误: {e}")


# 下载 GitHub 仓库的 zip 文件
def download_github_repo(repo_url, folder):
    # 将 GitHub 仓库链接转换为可下载的 zip 链接
    if repo_url.endswith('/'):
        repo_url = repo_url[:-1]
    repo_name = repo_url.split('/')[-1]
    user_name = repo_url.split('/')[-2]
    zip_url = f"https://github.com/{user_name}/{repo_name}/archive/refs/heads/main.zip"

    print(f"准备下载 GitHub 仓库: {repo_url},下载链接: {zip_url}")
    download_file(zip_url, folder, f"{repo_name}.zip")


# 遍历每篇文章,按大类创建文件夹并下载论文和代码
for paper in paper_data:
    section_folder = os.path.join(output_dir, paper['section'].replace(' ', '_'))
    if not os.path.exists(section_folder):
        os.makedirs(section_folder)

    title = paper['title'].replace('/', '-').replace(':', '-')  # 替换不合法字符
    paper_link = paper['paper_link']
    code_link = paper['code_link']

    # 直接在大类文件夹内下载论文
    paper_filename = title + ".pdf"
    print(f"准备下载论文: {paper_link}, 文件名: {paper_filename}")  # 调试信息
    download_file(paper_link, section_folder, paper_filename)

    # 如果有代码链接,并且是 GitHub 链接,下载 GitHub 仓库
    # if code_link and "github.com" in code_link:
    #     download_github_repo(code_link, section_folder)

print("所有文件已下载完成。")


http://www.kler.cn/a/568779.html

相关文章:

  • 游戏引擎学习第128天
  • 【C++经典例题】回文串判断:两种高效解法剖析
  • k8s 中各种发布方式介绍以及对比
  • 本地部署SenseVoice(包括离线设备操作)
  • Java语法基础知识点2
  • 达梦数据库系列之Mysql项目迁移为达梦项目
  • 基于html的俄罗斯方块小游戏(附程序)
  • 技术问题汇总:前端怎么往后端传一个数组?
  • DeepSeek 与大数据治理:AI 赋能数据管理的未来
  • 第十五届蓝桥杯最后一题 拔河问题
  • 各种传参形式
  • 深入探索 STM32 微控制器:从基础到实践
  • 每日一题——接雨水
  • 2.Exercise
  • 关于时间序列预测
  • 3.16 AI Agent 技术全景解析:从核心能力到企业级应用实践
  • GPT-4.5震撼登场,AI世界再掀波澜!(3)
  • Tkinter和爬虫写的知乎回答下载exe【免费下载】
  • 【STM32F103ZET6——库函数】6.PWM
  • 【软件安装】非华为手机安装华为电脑管家(14.0.5.8 C233)(附带安装包下载地址)