CNKI知网论文数据爬取

知网论文数据爬取

花了一些时间爬了一些知网数据。接口主要是:http://search.cnki.com.cn/ ,当然因为它搜索出来的文章介绍页是这样的:
CNKI知网论文数据爬取
缺少关键词呀,所以结合了一下学校的知网数据库,介绍页面基本上就有了需要的所有数据。
CNKI知网论文数据爬取
将两个介绍页面的链接进行了比较,发现可以先从第一个接口爬取论文介绍页链接,然后再做一些改变就可以利用第二个爬取数据了。

在此次实践中,我先爬取了所有“大数据”相关的期刊论文链接,然后再逐个爬取了其标题、作者、作者机构、关键词、摘要数据,结果存在excel表格中了。

# -*- coding:utf-8 -*-
import sys
import requests
from bs4 import BeautifulSoup
import math
import io
import time
import os

sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='utf8')

if __name__ == '__main__':
    #获取开始时间
    start=time.clock()
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36'
    }
    # 避免之前的内容重复爬取
    if os.path.exists('data-detail.txt'):
        print("存在输出文件,删除文件")
        os.remove('data-detail.txt')

# 获取页数,可以根据搜索关键词进行url修改,这里是“大数据”
index_url = r'http://search.cnki.com.cn/Search.aspx?q=大数据&rank=relevant&cluster=zyk&val=CJFDTOTAL'
htm1 = requests.get(index_url,headers=headers)
soup = BeautifulSoup(htm1.text, 'html.parser')
pagesum_text = soup.find('span', class_='page-sum').get_text()
maxpage = math.ceil(int(pagesum_text[7:-1]) / 15)
print('The total page is:', maxpage)

# 获取各检索结果文章链接
for i in range(0, maxpage):
    page_num = 15  # 一页共有15条搜索结果
    url = index_url + '&p=' + str(i * page_num)  # 构建url链接

    try:
        response = requests.get(url, headers=headers)
        soup = BeautifulSoup(response.text, 'html.parser')
    except:
        break

    f = open('data-detail.txt', 'a+', encoding='utf-8')
    all = soup.find_all('div', class_='wz_content')
    for string in all:
        item = string.find('a', target='_blank')  # 文章标题与链接
        href = item.get('href')  # 获取文章链接
        # title=item.get_text()#获取文章标题
        f.write(href + '\n')

    f.close()

    #获取结束时间
    end=time.clock()
    print('获取文章详情页链接共用时:%s Seconds'%(end-start))

获取详情数据:

import requests
from bs4 import BeautifulSoup
import xlwt
import re
import time

headers = {
    'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
    'Accept-Encoding':'gzip, deflate, sdch',
    'Accept-Language':'zh-CN,zh;q=0.8',
    'Connection':'keep-alive',
    'Host':'www.cnki.net',
    'Referer':'http://search.cnki.net/search.aspx?q=%E4%BD%9C%E8%80%85%E5%8D%95%E4%BD%8D%3a%E6%AD%A6%E6%B1%89%E5%A4%A7%E5%AD%A6&rank=relevant&cluster=zyk&val=CDFDTOTAL',
    'Upgrade-Insecure-Requests':'1',
    'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36'
}

if __name__=='__main__':
    start=time.clock()
#读取已经获得的文章链接
file=open('data-detail.txt',encoding="utf-8")

#xls创建与写入
wb=xlwt.Workbook('data_out.xsl')
sheet=wb.add_sheet('data-out')
sheet.write(0,0,'网址')
sheet.write(0,1,'标题')
sheet.write(0,2,'作者')
sheet.write(0,3,'机构')
sheet.write(0,4,'摘要')
sheet.write(0,5,'关键词')

lin_num=1
txt_num=1

for href in file:
    if  re.match(r'^(http://www.cnki.com.cn/Article/CJFDTOTAL)-\w{4}(\w*)',href):
        year=href[-14:-10]
        name=href[-18:-5]
        #含关键词的详情页链接
        paper_url= "http://kns.cnki.net/KCMS/detail/detail.aspx?dbcode=CJFQ&dbname=CJFDLAST" + year + "&filename=" +name
        try:

            html = requests.get(paper_url, headers=headers, timeout=500)
            soup = BeautifulSoup(html.text, 'html.parser')

        except:
            print("No result")
            break

        # 获取标题
        title = soup.find('h2', class_='title').get_text()

        # 获取作者
       # author = soup.find('div', class_='author').get_text() 比较简单,但是作者姓名容易黏在一起
        author=''
        for a in soup.find('div', class_='author').children:
            author+=(a.get_text()+';')

        # 获取机构
        orgn = soup.find('div', class_='orgn').get_text()

        # 获取摘要
        abstract = soup.find('span', id='ChDivSummary').get_text()

        #获取关键词,存在没有关键词的情况
        try:
            key = ''
            for k in soup.find('label', id='catalog_KEYWORD').next_siblings:
              ke = (k.get_text()).strip()
              key += ke.replace('\r\n', '')
        except:
          pass

        print(title)

        line=paper_url+'\t'+str(title)+'\t'+str(author)+'\t'+str(orgn)+'\t'+str(abstract)+'\t'+str(key)+'\n'
        outstring=line.split('\t')
        for i in range(len(outstring)):
            #写入
           sheet.write(lin_num,i,outstring[i])
        print('写入第'+str(lin_num)+'行')
        lin_num+=1

        #保存成xx文件
        wb.save('data_out_'+str('大数据'+'.xls'))

file.close()
end=time.clock()
print('完成论文数据获取共用时:%s Seconds'%(end-start))

参考项目:
https://github.com/qiuqingyu/CNKICrawler