IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> Python知识库 -> 谷歌学术文献信息爬取及文献下载 -> 正文阅读

[Python知识库]谷歌学术文献信息爬取及文献下载

两个py文件

起主要作用的Search&Download.py

# -*- coding: utf-8 -*-

import requests
from bs4 import BeautifulSoup
from Download import Hubber
import xlwt,os
from time import sleep
from tqdm import tqdm


TotalNum=0
class Article(object):
    title = ""
    article_link = ""
    authors = ""
    authors_link = ""
    abstract = ""
    def __init__(self):
        title = "New Paper"

def save_xls(sheet, paper):
    # 将数据按列存储入excel表格中
    global TotalNum
    sheet.write(TotalNum, 0, TotalNum)
    sheet.write(TotalNum, 1, paper.title)
    sheet.write(TotalNum, 2, paper.article_link)
    sheet.write(TotalNum, 3, paper.journal)
    sheet.write(TotalNum, 4, paper.authors_link)
    sheet.write(TotalNum, 5, paper.abstract)
    TotalNum += 1

head = { \
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117 Safari/537.36' \
        }  # 20210607更新,防止HTTP403错误
article_titles = []
article_links = []

def GetInfo(sheet,url):
  r = requests.get(url, headers=head)
  r.raise_for_status()
  r.encoding = r.apparent_encoding
  soup = BeautifulSoup(r.text, "html.parser")
  #print("\n"+soup)
  articles = soup.find_all(class_="gs_ri")
  for article in articles:
      paper =Article()
      try:
          title = article.find('h3')
          paper.title = title.text
          #print("\n"+paper.title)
          article_titles.append(paper.title)
          paper.article_link = title.a.get('href')
          #print("\n"+paper.article_link)
          article_links.append(paper.article_link)

          journal = article.find(class_="gs_a")
          paper.journal =journal.text
          #print("\n"+paper.authors)
          authors_addrs = journal.find_all('a')
          for authors_addr in authors_addrs:
              #print("\n"+authors_addr.get('href'))
              paper.authors_link=paper.authors_link +(authors_addr.get('href'))+"\n"

          abstract = article.find(class_="gs_rs")
          paper.abstract = abstract.text
          #print("\n"+paper.abstract)
      except:
          continue
      save_xls(sheet,paper)
  return


def getArticle(article_titles,article_links):
    dir = ".\\Articles\\" +keyword +"\\"
    #print (dir)
    if os.path.exists(dir) == False:
        os.mkdir(dir)
    for k in tqdm(range(len(article_titles))):
        article_titles[k]="{0}".format(article_titles[k].replace(':', ' ')).replace('.', '')
        path = dir + article_titles[k] + ".pdf"
        #print("\n"+path)
        try:
            Hubber.getPDF(article_links[k],path)
            sleep(0.5)
        except:
            continue

if __name__ == '__main__':
    myxls = xlwt.Workbook()
    sheet1 = myxls.add_sheet(u'PaperInfo', True)
    column = ['序号', '文章题目','文章链接','期刊', '作者链接', '摘要']
    for i in range(0, len(column)):
        sheet1.write(TotalNum, i, column[i])
    TotalNum+=1

    keyword=input("keywords is?\n")
    #keyword = diabetes and conjunctiva and (microcirculation or microvasculature)
    #print("\n"+keyword)
    key = keyword.replace(" ","+")
    info = keyword + "_PaperInfo.xls"

    print("\n"+"检索中……")
    if os.path.exists(info) == True:
        print("\n" + "PaperInfo already exists!")
    else:
        start = 0
        for i in tqdm(range(10)):
            url = 'https://xs.dailyheadlines.cc/scholar?start=' + str(start) + '&q=' + key + '&hl=zh-CN&as_sdt=0,5'
            start = start + 10
            GetInfo(sheet1,url)
            myxls.save(keyword+'_PaperInfo.xls')
            sleep(0.5)
    print("\n"+"检索完成")

    print("\n"+"下载中……")
    if len(article_titles) != 0:
        getArticle(article_titles, article_links)
    else:
        import xlrd
        data = xlrd.open_workbook(info)
        table = data.sheet_by_index(0)
        article_titles = table.col_values(1)[1:]
        article_links = table.col_values(2)[1:]
        #print("\n"+article_titles)
        #print("\n"+article_links)
        getArticle(article_titles, article_links)
        print("\n"+ "下载完成")

起辅助作用的Download.py,可将更多网站补充进去!?

import os.path
import re
import requests
from bs4 import BeautifulSoup

class Hubber:
    head = { \
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117 Safari/537.36' \
        }  # 20210607更新,防止HTTP403错误

    def pdf_hub(url,path):
        try:
            pdf = requests.get(url, headers=Hubber.head)
            with open(path, "wb") as f:
                f.write(pdf.content)
            print("\n"+"pdf found directly!")
        except:
            print("\n"+"failed to download pdf directly!\n" +url)
            Hubber.err_log(url)
    def sci_hub(path,doi):
        doi = str(doi).split("https://doi.org/")[1]
        url = "https://www.sci-hub.ren/doi:" + doi + "#"
        r = requests.get(url, headers=Hubber.head)
        r.raise_for_status()
        r.encoding = r.apparent_encoding
        soup = BeautifulSoup(r.text, "html.parser")
        download_url = soup.iframe.attrs["src"]
        try:
            download_r = requests.get(download_url, headers=Hubber.head)
            download_r.raise_for_status()
            with open(path, "wb+") as temp:
                temp.write(download_r.content)
                print("\n"+"Article downloaded by doi!")
        except:
            print("\n"+"failed to download pdf by doi!\n" +url)
            Hubber.err_log(url)

    def err_log(url):
        with open("download_err.txt", "a+", encoding="utf-8") as error:
            error.write("PDF not found,download link may be: \n"+url +"\n")

    def getSoup(url):
        r = requests.get(url, headers=Hubber.head)
        r.raise_for_status()
        r.encoding = r.apparent_encoding
        soup = BeautifulSoup(r.text, "html.parser")
        return soup

    def getPDF(url,path):
        if os.path.exists(path) == True:
            print("\n" + "Article already exists")
        else:
            if (len(re.findall('pdf', url)) != 0):
                print ("\n"+'pdf link already!')
                Hubber.pdf_hub(url,path)
            elif re.match("https://www.sci-hub.ren/",url):
                print("\n" + 'sci_hub link!')
                url = str(url).replace("https://www.sci-hub.ren/","https://doi.org/")
                Hubber.sci_hub(path,url)
            #if pdf can be easily found!
            elif re.match("https://academic.oup.com/", url):
                soup = Hubber.getSoup(url)
                pdf_link ="https://academic.oup.com"+soup.find(class_="al-link pdf article-pdfLink").get('href')
                #print("\n"+pdf_link)
                Hubber.pdf_hub(pdf_link,path)
                '''
                doi = soup.select('div[class="ww-citation-primary"]')[0].a.get('href')
                #print("\n"+doi)
                Hubber.sci_hub(path,doi)
                '''
            elif re.match("https://content.iospress.com/", url):
                soup = Hubber.getSoup(url)
                pdf_link = soup.find(class_="btn btn-download btn-right get-pdf").get('href')
                # print("\n"+pdf_link)
                Hubber.pdf_hub(pdf_link, path)
            elif re.match("https://wwwnature.53yu.com/", url):
                soup = Hubber.getSoup(url)
                pdf_link = soup.find(class_="c-pdf-download__link").get('href')
                #print("\n"+pdf_link)
                Hubber.pdf_hub(pdf_link, path)
            elif re.match("https://bjo.bmj.com/", url):
                soup = Hubber.getSoup(url)
                pdf_link = soup.find(class_="article-pdf-download").get('href')
                pdf_link = "https://bjo.bmj.com" + pdf_link
                #print("\n"+pdf_link)
                Hubber.pdf_hub(pdf_link,path)
            elif re.match("https://jamanetwork.com/", url):
                soup = Hubber.getSoup(url)
                pdf_link = soup.find(class_="toolbar-tool toolbar-pdf al-link pdfaccess").get('data-article-url')
                pdf_link = "https://jamanetwork.com" + pdf_link
                #print("\n"+pdf_link)
                Hubber.pdf_hub(pdf_link, path)

            #if pdf can't be easily found,but doi can!
            elif re.match("https://sciencedirect.53yu.com/", url):
                soup = Hubber.getSoup(url)
                doi = soup.find(class_="doi").get('href')
                Hubber.sci_hub(path, doi)
            elif re.match("https://diabetes.diabetesjournals.org/", url):
                soup = Hubber.getSoup(url)
                doi = soup.select('.citation-doi')[0].a.get('href')
                Hubber.sci_hub(path, doi)
            elif re.match("https://journals.lww.com/", url):
                soup = Hubber.getSoup(url)
                doi = "https://doi.org/" + str(soup.find(id="ej-journal-doi").text).split("doi: ")[1]
                Hubber.sci_hub(path, doi)
            else:
                '''
                https://europepmc.org/
                https://iovs.arvojournals.org/
                https://linkspringer.53yu.com/
                '''
                print("\n"+"To be prettified!Download link may be: " +"\n" +url)
                Hubber.err_log(url)

if __name__ == '__main__' :
    url = "https://www.nature.com/articles/s41598-021-87315-7.pdf"
    url1 = "https://www.sci-hub.ren/doi:10.1067/mva.2003.139#"
    url2 = "https://www.sci-hub.ren/doi:10.1067/mva.2003.139#"
    Hubber.getPDF(url,"test.pdf")
    Hubber.getPDF(url1,"test1.pdf")
    Hubber.getPDF(url2,"test2.pdf")

  Python知识库 最新文章
Python中String模块
【Python】 14-CVS文件操作
python的panda库读写文件
使用Nordic的nrf52840实现蓝牙DFU过程
【Python学习记录】numpy数组用法整理
Python学习笔记
python字符串和列表
python如何从txt文件中解析出有效的数据
Python编程从入门到实践自学/3.1-3.2
python变量
上一篇文章      下一篇文章      查看所有文章
加:2022-01-17 11:28:10  更:2022-01-17 11:28:41 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/16 2:28:36-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码