记第一次知网爬虫实践

由于工作原因,需要下载大量知网上的统计数据,便学习了用python写爬虫,之后效率提高了n倍,代码如下:

# -*- coding: utf-8 -*-
import urllib.request
from bs4 import BeautifulSoup
import requests
import time
import random
import re


def get_result(ybcode,page=1):  #数据的请求
    data = {'ybcode': ybcode, 'entrycode': '', 'page': page, 'pagerow': '20'}
    headers = {
        'Content-Type': 'application/x-www-form-urlencoded',
    }
    url = "http://data.cnki.net/Yearbook/PartialGetCatalogResult"  
    params = urllib.parse.urlencode(data).encode(encoding='utf-8')
    req = urllib.request.Request(url, params, headers)
    r = urllib.request.urlopen(req)
    res = str(r.read(),'utf-8')
    return res

def get_pageno(ybcode):  #获取总页数
    soup = BeautifulSoup(get_result(ybcode), 'lxml')
    pages=int(soup.select('.s_p_listl')[0].get_text().split("共")[2].split('页')[0])
	print ('总共'+pages+'页')
    return pages


def dataclear(data):  #数据的清理,除去文本中所有的\n和\r
    data=re.sub('\n+',' ',data)
    data = re.sub('\r+', ' ', data)
    data=re.sub(' +',' ',data)
    return data


def filedata(ybcode): #下载知网的统计年鉴之类的所有excel表
    pageno=get_pageno(ybcode)
    for i in range(1,pageno+1,1):  
        print ('########################################当前第'+str(i)+'页###################################')
        soup=BeautifulSoup(get_result(ybcode,i),'lxml')
        for j in soup.select('tr'):
            s=BeautifulSoup(str(j),'lxml')
            if len(s.select('img[src="/resources/design/images/nS_down2.png"]'))==0:
                pass
            else:
                try:
                    if len(BeautifulSoup(str(j), 'lxml').select('td:nth-of-type(3) > a'))>=2:
                        title= str(BeautifulSoup(str(j), 'lxml').select('td:nth-of-type(1) > a')[0].get_text())
                        url= 'http://data.cnki.net'+BeautifulSoup(str(j), 'lxml').select('td:nth-of-type(3) > a')[1].get('href')
                        title=dataclear(title) #若不清洗数据,则文件名中会包含\n等特殊字符,导致文件下载错误
                        filedown(title,url)
                        print(title)
                except Exception as e:
                    print ('error:-------------------'+str(e))
                    pass

def filedown(title,url):  #文件下载函数
    try:
        r = requests.get(url)
        with open(title + ".xls", "wb") as code:
            code.write(r.content)
    except Exception as e:
        pass
    x = random.randint(1,2)
    time.sleep(x)

if __name__=='__main__':
    ybcode = 'N2013060059'  #更改此项可下载其他年鉴
    filedata(ybcode)


  • 6
    点赞
  • 70
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值