【问题标题】:Python: Download papers from ScienceDirect by DOI with requestsPython:通过 DOI 请求从 ScienceDirect 下载论文
【发布时间】:2021-11-29 22:27:51
【问题描述】:

我有一个我感兴趣的论文 DOI 的 Excel 列表。基于此列表,我想下载所有论文。

按照他们的文档中的建议,我尝试按照请求进行操作。但是我得到的 pdf 文件已损坏。它们只是一些 KB 大。我将 chunk_size 从 None 更改为 1024*1024 几次,并且我已经阅读了很多帖子。没有任何帮助。

请问你有什么想法?

import pandas as pd
import os
import requests


def get_pdf(doi, file_to_save_to):
    url = 'http://api.elsevier.com/content/article/doi:'+doi+'?view=FULL'
    headers = {
        'X-ELS-APIKEY': "keykeykeykeykeykey",
        'Accept': 'application/pdf'
    }
    r = requests.get(url, stream=True, headers=headers)
    if r.status_code == 200:
        for chunk in r.iter_content(chunk_size=1024*1024):
            file_to_save_to.write(chunk)
            return True


doi_list = pd.read_excel('list.xls')
doi_list.columns = ['DOIs']
count = 0
for doi in doi_list['DOIs']:
    doi = doi.replace('DOI:','')
    pdf = doi.replace('/','%')
    if not os.path.exists(f'path/{pdf}.pdf'):
        file = open(f'path/{pdf}.pdf', 'wb') 
        get_pdf(doi, file)
        count += 1
        print(f"Dowloaded: {count} of {len(doi_list['DOIs'])} articles")

【问题讨论】:

  • 您流式传输文件是否有特殊原因?

标签: python python-requests doi


【解决方案1】:

我认为您的问题是for chunk in r.iter_content 中的return True。使用该行,您将只能编写大小为 chunk_size 的 PDF 的一大块。

您还应该使用with 打开文件;照原样,您永远不会关闭文件句柄。

import pandas as pd
import os
import requests


HEADERS = {
    'X-ELS-APIKEY': "keykeykeykeykeykey",
    'Accept': 'application/pdf'
}


def get_pdf(doi, file_to_save_to):
    url = f'http://api.elsevier.com/content/article/doi:{doi}?view=FULL'
    with requests.get(url, stream=True, headers=HEADERS) as r:
        if r.status_code == 200:
            for chunk in r.iter_content(chunk_size=1024*1024):
                file_to_save_to.write(chunk)


doi_list = pd.read_excel('list.xls')
doi_list.columns = ['DOIs']
count = 0
for doi in doi_list['DOIs']:
    doi = doi.replace('DOI:','')
    pdf = doi.replace('/','%')
    if not os.path.exists(f'path/{pdf}.pdf'):
        with open(f'path/{pdf}.pdf', 'wb') as file:
            get_pdf(doi, file)
        count += 1
        print(f"Dowloaded: {count} of {len(doi_list['DOIs'])} articles")

【讨论】:

  • 感谢您的意见!我更改了它,但 pdf 文件仍然有 100 KB 大。所以,我只能看到第一页,而看不到文档的其余部分。
  • @renrei 你能以某种方式分享程序的变化吗?
  • @AlexanderCécile,它看起来和柯克建议的完全一样
  • @renrei 您能否确认在重试之前删除了所有现有文件?
  • requests.readthedocs.io/en/master/user/advanced/… 也许您需要使用 with 语句,或者刷新请求。我将更新代码示例
猜你喜欢
  • 2013-10-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-14
  • 2023-03-02
  • 1970-01-01
  • 2013-08-20
  • 1970-01-01
相关资源
最近更新 更多