爬虫批量下载科研论文(SciHub)

news2024/10/5 15:30:21

系列文章目录

利用 eutils 实现自动下载序列文件


提示:写完文章后,目录可以自动生成,如何生成可参考右边的帮助文档

文章目录

  • 系列文章目录
  • 前言
  • 一、获取文献信息
  • 二、下载文献PDF文件
  • 参考


前言

大家好✨,这里是bio🦖。这次为大家带来自动收集文献信息、批量下载科研论文的脚本(只能批量下载公布在sci-hub上的科研论文)。平常阅读文献时只需要一篇一篇下载即可,并不需要用到批量下载的操作。但有时需要对某领域进行总结或者归纳,就可以考虑使用批量下载咯~

导师下令找文献,学生偷偷抹眼泪。
文献三千挤满屏,只下一篇可不行。
作息紊乱失双休,日夜不分忘寝食。
满腔热血搞科研,一盆冷水当头洛。
(打油诗人作)


一、获取文献信息

每个人的研究领域不一样,获取文献信息的方式不一样。这里以Pubmed1为例,PubMed是主要用于检索MEDLINE数据库中,生命科学和生物医学引用文献及索引的免费搜索引擎。之前爬取冠状病毒核酸数据使用过eutils,本篇博客也使用eutils去获取文献信息,关于eutils的介绍可以看利用 eutils 实现自动下载序列文件 。这里就不做介绍~

首先构造搜索url,其中term是你检索的关键词,year对应文献发表日期,API_KEY能够让你在一秒内的访问次数从3次提升到10次。这里将term替换为Machine learningyear替换为2022。然后使用requests库获取该url的对应的信息,在使用BeautifulSoup库将其转化为html格式。

https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=pubmed&api_key={API_KEY}&term={term}+{year}[pdat]

代码如下:

import pandas as pd
import requests
from bs4 import BeautifulSoup
import math
import re
import time

API_KEY = "Your AIP KEY"
term = "Machine Learning"
year = "2022"
url_start = f'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=pubmed&api_key={API_KEY}&term={term}+{year}[pdat]'
info_page = BeautifulSoup(requests.get(url_start, timeout=(5, 5)).text, 'html.parser')

爬取的结果如下,可以看到结果主要包括许多PMID。然后包括的信息总数<count>31236</count>、最大返回数<retmax>20</retmax>以及结果开始的序号<retstart>0</retstart>。下一步就是根据id获取文章对应的信息。

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE eSearchResult PUBLIC "-//NLM//DTD esearch 20060628//EN" "https://eutils.ncbi.nlm.nih.gov/eutils/dtd/20060628/esearch.dtd">

<esearchresult><count>31236</count><retmax>20</retmax><retstart>0</retstart><idlist>
<id>37878682</id>
<id>37873546</id>
<id>37873494</id>
... # omitting many results
<id>37786662</id>
<id>37780106</id>
<id>37776368</id>
</idlist><translationset><translation> <from>Machine Learning</from> <to>"machine learning"[MeSH Terms] OR ("machine"[All Fields] AND "learning"[All Fields]) OR "machine learning"[All Fields]</to> </translation></translationset><querytranslation>("machine learning"[MeSH Terms] OR ("machine"[All Fields] AND "learning"[All Fields]) OR "machine learning"[All Fields]) AND 2022/01/01:2022/12/31[Date - Publication]</querytranslation></esearchresult>

可以看到结果也是31236条记录,爬取的信息忠实于实际的信息,可以放心食用~
在这里插入图片描述

获取文章的信息也是相同的步骤,首先构造url,然后爬取对应的信息,直接上代码:

API_KEY = "Your AIP KEY"
id_str = '37878682'
url_paper = f'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=pubmed&api_key={API_KEY}&id={id_str}&rettype=medline&retmode=text'
paper_info = BeautifulSoup(requests.get(url_paper, timeout=(5, 5)).text, 'html.parser')

结果如下,包括PMID、DOI、摘要、作者、单位、发表年份等等信息,你可以从这一步获得的信息中获取你需要的信息如DOI。接下来的就是要爬取文献对应的PDF文件。这是最关键的一步。

PMID- 37878682
OWN - NLM
STAT- Publisher
LR  - 20231025
IS  - 2047-217X (Electronic)
IS  - 2047-217X (Linking)
VI  - 12
DP  - 2022 Dec 28
TI  - Computational prediction of human deep intronic variation.
LID - giad085 [pii]
LID - 10.1093/gigascience/giad085 [doi]
AB  - BACKGROUND: The adoption of whole-genome sequencing in genetic screens has 
      facilitated the detection of genetic variation in the intronic regions of genes, 
      far from annotated splice sites. However, selecting an appropriate computational 
      tool to discriminate functionally relevant genetic variants from those with no 
      effect is challenging, particularly for deep intronic regions where independent 
      benchmarks are scarce. RESULTS: In this study, we have provided an overview of 
      the computational methods available and the extent to which they can be used to 
      analyze deep intronic variation. We leveraged diverse datasets to extensively 
      evaluate tool performance across different intronic regions, distinguishing 
      between variants that are expected to disrupt splicing through different 
      molecular mechanisms. Notably, we compared the performance of SpliceAI, a widely 
      used sequence-based deep learning model, with that of more recent methods that 
      extend its original implementation. We observed considerable differences in tool 
      performance depending on the region considered, with variants generating cryptic 
      splice sites being better predicted than those that potentially affect splicing 
      regulatory elements. Finally, we devised a novel quantitative assessment of tool 
      interpretability and found that tools providing mechanistic explanations of their 
      predictions are often correct with respect to the ground - information, but the 
      use of these tools results in decreased predictive power when compared to black 
      box methods. CONCLUSIONS: Our findings translate into practical recommendations 
      for tool usage and provide a reference framework for applying prediction tools in 
      deep intronic regions, enabling more informed decision-making by practitioners.
CI  - (c) The Author(s) 2023. Published by Oxford University Press GigaScience.
FAU - Barbosa, Pedro
AU  - Barbosa P
AUID- ORCID: 0000-0002-3892-7640

在进行尝试下载文献之前,构建两个函数便于批量爬取信息。get_literature_idget_detailed_info分别获取文献的PMID以及详细信息。

def get_literature_id(term, year):
    API_KEY = "Your AIP KEY"
    # pdat means published date, 2020[pdat] means publised literatures from 2020/01/01 to 2020/12/31
    url_start = f'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=pubmed&api_key={API_KEY}&term={term}+{year}[pdat]'
    time.sleep(0.5)
    info = BeautifulSoup(requests.get(url_start, timeout=(5, 5)).text, 'html.parser')
    time.sleep(0.5)
    # translate str to int
    year_published_count = int(info.find('count').text)
    
    id_list = [_.get_text() for _ in info.find_all('id')]

    for page in range(1, math.ceil(year_published_count/20)):
        url_page = f'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=pubmed&api_key={API_KEY}&term=pbmc+AND+single+cell+{year}[pdat]&retmax=20&retstart={page*20}'
        time.sleep(0.5)
        info_page = BeautifulSoup(requests.get(url_page, timeout=(5, 5)).text, 'html.parser')
        id_list += [_.get_text() for _ in info_page.find_all('id')]

    return id_list, year_published_count

def get_detailed_info(id_list):
    API_KEY = "Your AIP KEY"
    # PMID DOI PMCID Title Abstract Author_1st Affiliation_1st Journel Pulication_time
    extracted_info = []
    for batch in range(0, math.ceil(len(id_list)/20)):
        id_str = ",".join(id_list[batch*20: (batch+1)*20])
        detailed_url = f'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=pubmed&api_key={API_KEY}&id={id_str}&rettype=medline&retmode=text'
        time.sleep(0.5)
        detailed_info = BeautifulSoup(requests.get(detailed_url, timeout=(5, 5)).text, 'html.parser')
        literature_as_line_list = detailed_info.text.split('\nPMID')[1:]

        for literature in literature_as_line_list:
            # PMID
            pmid = literature.split('- ')[1].split('\n')[0]
            # DOI
            if '[doi]' in literature:
                doi = literature.split('[doi]')[0].split(' - ')[-1].strip()
            else:
                doi = ""
            # PMCID
            if "PMC" in literature:
                pmcid = literature.split('PMC -')[1].split('\n')[0].strip()
            else:
                pmcid = ""
            # Title
            title = re.split(r'\n[A-Z]{2,3}\s', literature.split('TI  - ')[1])[0].replace("\n      ", "")
            if '\n' in title:
                title = title.replace("\n      ", "")
            # Abstract
            abstract = literature.split('AB  - ')[1].split(' - ')[0].replace("\n      ", "").split('\n')[0]
            # Author_1st
            author = literature.split('FAU - ')[1].split('\n')[0]
            # Affiliation_1st
            tmp_affiliation = literature.split('FAU - ')[1]
            if "AD  - " in tmp_affiliation:
                affiliation = tmp_affiliation.split('AD  - ')[1].replace("\n      ", "").strip('\n')
            else:
                affiliation = ""

            # Journel
            journel = literature.split('TA  - ')[1].split('\n')[0]
            # Publication time
            publication_time = literature.split('SO  - ')[1].split(';')[0].split('. ')[1]
            if ':' in publication_time:
                publication_time = publication_time.split(':')[0]

            extracted_info.append([pmid, doi, pmcid, title, abstract, author, affiliation, journel, publication_time])

    return extracted_info

爬取的部分结果如下图所示。有些文章没有DOI号,不信的话可以尝试在PubMed中搜索该文章对应的PMID33604555看看~。
在这里插入图片描述

二、下载文献PDF文件

关于下载文献的PDF文件,这里是从SciHub中爬取的,不是从期刊官方,部分文章可以没有被SciHub收录或者收录的预印版,因此,不能 保证上文中获取的信息就能从SciHub中全部下载成功。如果不能访问SciHub,自然就不能爬取对应的内容了,可以考虑买个VPN,科学上网~。

爬取SciHub上的文章需要构建一个访问头的信息,不然回返回403禁止访问。然后将获取的内容保存为PDF格式即可。其中从SciHub中爬取文献PDF文件参考了 用Python批量下载文献2

data = pd.read_csv('/mnt/c/Users/search_result.csv')
doi_data = data[~data['DOI'].isna()]
doi_list = doi_data["DOI"].tolist()
pmid_list = doi_data["PMID"].tolist()
for doi, pmid in zip(doi_list, pmid_list):
    download_url = f'https://sci.bban.top/pdf/{doi}.pdf?#view=FitH'
    headers = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.63 Safari/537.36"}
    literature = requests.get(download_url, headers=headers)
    if literature.status_code != 200:
        print(f"this paper may have not downloading permission, it's doi: {doi}")
    else:
        with open(f'/mnt/c/Users/ouyangkang/Desktop/scraper_literature/{pmid}.pdf', 'wb') as f:
            f.write(literature.content)

爬取结果如下图所示,成功下载了199篇~(这里的关键词不是机器学习,提供的doi数量是522,下载成功率为38%)。
在这里插入图片描述


参考


  1. .Pubmed official websity ↩︎

  2. 用Python批量下载文献 ↩︎

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1138925.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

PHP函数的定义与最简单后门原理

PHP函数的定义与最简单后门原理 文章目录 PHP函数的定义与最简单后门原理函数的定义函数调用的过程变量的范围局部变量全局变量 可变函数动态函数 PHP 最简单后门原理分析 函数的定义 使用function关键字来定义一个函数定义函数的函数名避开关键字形式参数是传递映射的实际参数…

css实现圆形进度条

能用现成组件就用&#xff0c;实现不行再自己写&#xff0c;因为牵扯到上传文件&#xff0c;进度实时出不来&#xff0c;所以只能使用dom元素操作&#xff1b; 1.实现 效果&#xff1a; 上图是100%&#xff0c;如果需要根据百分比显示&#xff0c;我们需要看下代码里面left和…

高通平台GPIO引脚复用指导

高通平台GPIO引脚复用指导 1. 概述1.1 平台有多少个GPIO&#xff1f;1.2 这些GPIO都有哪些可复用的功能&#xff1f; 2. 软件配置2.1 TZ侧GPIO配置2.2 SBL侧GPIO配置2.3 AP侧GPIO配置2.3.1 Linux DTS机制与设备驱动模型概述2.3.2高通平台的pinctrl控制器2.3.2.1 SDX12 CPU pinc…

axios封装以及详细用法

文章目录 axios用法(这里没有封装&#xff0c;下面有封装好的get&#xff0c;post方法&#xff0c;在axios封装里面)get &#xff0c;delete方法post&#xff0c;put方法 axios具体封装axios 具体参数配置 axios用法(这里没有封装&#xff0c;下面有封装好的get&#xff0c;pos…

全球创业浪潮:跨境电商的创新时代

在当今数字化的时代&#xff0c;全球商业局势正在发生深刻的变革&#xff0c;而跨境电商正处于这一变革的前沿。随着全球创业浪潮的崛起&#xff0c;跨境电商行业正在迎来一个充满创新活力的时代。这篇文章将深入探讨跨境电商如何在全球创业浪潮中扮演关键角色&#xff0c;以及…

国际腾讯云自主拼装直播 URL教程!!!

注意事项 创建转码模板 并与播放域名进行 绑定 后&#xff0c;转码配置后的直播流&#xff0c;需将播放地址的 StreamName 拼接为 StreamName_转码模板名称&#xff0c;更多详情请参见 播放配置。 前提条件 已注册腾讯云账号&#xff0c;并开通 腾讯云直播服务。 已在 域名…

Parallels Desktop 19.1.0 pd Mac 虚拟机解决方案

Parallels Desktop 是功能最强大灵活度最高的虚拟化方案&#xff0c;无需重启即可在同一台电脑上随时访问 Windows 和 Mac 两个系统上的众多应用程序。从仅限于 PC 的游戏到生产力软件&#xff0c;Parallels Desktop 都能帮您实现便捷使用。 Parallels Desktop 19.1.0 应用介绍…

云服务器的先驱,亚马逊云科技海外云服务器领军者

随着第三次工业革命的发展&#xff0c;移动互联网技术带来的信息技术革命为我们的生活带来了极大的便捷。其中&#xff0c;不少优秀的云服务器产品发挥了不可低估的作用&#xff0c;你或许听说过亚马逊云科技、谷歌GCP、IBM Cloud等优秀的海外云服务器。那么云服务器有哪些&…

【k8s】kubeadm安装k8s集群

一、环境部署 master192.168.88.10docker、kubeadm、kubelet、kubectl、flannelnode01192.168.88.20docker、kubeadm、kubelet、kubectl、flannelnode02192.168.88.30docker、kubeadm、kubelet、kubectl、flannelhub.lp.com192.168.88.40 docker、docker-compose harbor-offli…

SDL窗口创建以及简单显示(1)

项目创建步骤 1. 使用Qt Creator创建一个C项目 2. 将SDL库文件放到源文件目录下 在项目pro文件中添加库文件 win32{INCLUDEPATH $$PWD/SDL2-2.0.10/includeLIBS $$PWD/SDL2-2.0.10/lib/x86/SDL2.lib } 使用SDL创建一个窗口 #include <stdio.h>#include <SDL.h>…

HarmonyOS开发:探索组件化模式开发

前言 组件化一直是移动端比较流行的开发方式&#xff0c;有着编译运行快&#xff0c;业务逻辑分明&#xff0c;任务划分清晰等优点&#xff0c;针对Android端的组件化&#xff0c;之前有比较系统的总结过相关文章&#xff0c;感兴趣的朋友&#xff0c;可以查看&#xff0c;点击…

java后端返回给前端不为空的属性

问题背景&#xff1a; 目前遇到的一个问题。一个对象里面定义了数组、集合、和字符串属性等&#xff0c;但是返回给前端的时候数组和集合都是空的&#xff0c;前端接收到的是“” 一个空字符。然后保存的时候又把空字符传给后端&#xff0c;出现了数据结构不匹配导致报错。 解…

二、【常用的几种抠图方式一】

文章目录 选框抠图快速选择工具抠图魔棒工具抠图对象选择工具抠图套索工具抠图多边形套索工具抠图磁性套索工具抠图 选框抠图 选框工具抠图适合规则的图形&#xff0c;如下图先使用选框工具框出对象的图轮廓&#xff0c;然后再选择并遮住在里边擦出图形的边缘&#xff0c;根据…

Hi3516DV500部署paddle版型分析模型记录

原版模型测试并导出onnx paddle 版面分析-> https://github.com/PaddlePaddle/PaddleOCR/blob/release/2.7/ppstructure/layout/README_ch.md 测试 python3 deploy/python/infer.py \ --model_dirmodel/picodet_lcnet_x1_0_fgd_layout_cdla_infer/ \ --image_fil…

Openssl数据安全传输平台011:base64的使用

文章目录 1 base641.1 概念1.2 应用场景 2 base64 算法 &#xff08;重要&#xff09;3 openssl 中base64的使用3.1 BIO 操作3.2 base64 编码 -> bio链的写操作3.3 base64 解码 -> bio链的读操作 1 base64 1.1 概念 Base64是一种基于64个可打印字符来表示二进制数据的表…

CTF-Web(3)文件上传漏洞

笔记目录 CTF-Web(2)SQL注入CTF-Web(3)文件上传漏洞 1.WebShell介绍 (1)一句话木马定义 一种网页后门&#xff0c;以asp、php、jsp等网页文件形式存在的一种命令执行环境&#xff0c;而 一句话木马往往只有一行WebShell代码。 作用&#xff1a; 攻击获得网站控制权限 查看、修改…

p5.js 状态管理

本文简介 带尬猴&#xff0c;我是德育处主任 原生 canvas 提供了 save() 和 restore() 两个方法去管理画布状态。p5.js 作为一个 canvas 库&#xff0c;也理所当然的提供了状态管理的方法。在 p5.js 里这两个方法叫 push() 和 pop()。 本文主要讲解 p5.js 的 push() 和 pop()…

Q41F-25C软密封球阀型号解析

Q41F-25C型号字母含义解析 Q41F-25C是德特森阀门常用的软密封球阀型号字母分别代表的意思是: Q——代表阀门类型《球阀》 4——代表连接方式《法兰》 1——代表结构形式《浮动式》 F——代表阀座材料《聚四氟乙烯PTFE》 -《分隔键》 25——代表公称压力《2.5MPA》 C——…

Ubuntu编译 PCL 1.13.1 详细流程

Ubuntu编译 PCL 1.13. 详细流程 一、编译环境二、虚拟机准备1. 虚拟机扩容2. 配置交换分区 三、Cmake - gui 生成 MakeFile1. 解决 flann 依赖问题2. 配置 Cmake 四、编译安装1.编译&#xff1a;2. 安装 一、编译环境 Ubuntu&#xff1a;Ubuntu 20.04 VMware&#xff1a;VMwar…

护眼灯亮度多少合适?2023最专业的护眼灯品牌推荐

护眼灯是现在广大台灯消费者使用最多的一个灯具种类&#xff0c;它主要带来了更加柔和的用光环境与护眼效果。而其中&#xff0c;护眼灯的国家级照度又是其挑选的重点&#xff0c;那A级跟AA级具体有啥区别呢&#xff1f;首先&#xff0c;护眼台灯的国家A级或者AA级标准&#xf…