年度巨作!The big data of The Plant Cell : PC年度大数据抓取及分析(一)

只是突然冒出这么一个想法,在读文献的时候。
好久没写爬虫了,顺便还可以练练R。

The Plant Cell,1989年创刊,月刊,5年IF:10.529。
毫无疑问是植物学最顶级的杂志,植物人的梦想。

我大概的目标是抓取每一篇研究文章的摘要,顺带通讯作者和作者所在机构,之后看看用分词的包把摘要进行分词,最后计算词频,以及作者、机构的频数。

首先进入PC网站,随便找一篇文章进入它的摘要界面:

右键查看网页源代码,OK,可以爬取,顺带连作者机构都在一个页面,一起抓了。
再观察网页地址,发现28/11/2715,28为年份数,2016年的刊物都为28,11为月份数,代表11月,2715则为页码。

下图为2016年PC的月刊详情:

所以现在要从哪里获得这些文章的页码信息呢,发现在每一月期刊下有一个TOC:

TOC就是table of content,点开一看是个PDF,就相当于目录的意思。

目录上就有页码,似乎只要把这些页码爬下来就可以了。
但由于这个TOC是PDF,把它爬下来之后还不能直接解析,所以我又找了一个解析PDF文件的包,pdfminer,直接开搞!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
from urllib2 import urlopen
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from pdfminer.pdfpage import PDFPage
from cStringIO import StringIO
import re
def convert_pdf_to_txt(fp):
rsrcmgr = PDFResourceManager()
retstr = StringIO()
codec = 'utf-8'
laparams = LAParams()
device = TextConverter(rsrcmgr, retstr, codec=codec, laparams=laparams)
interpreter = PDFPageInterpreter(rsrcmgr, device)
password = ""
maxpages = 0
caching = True
pagenos=set()
for page in PDFPage.get_pages(fp, pagenos, maxpages=maxpages, password=password,caching=caching, check_extractable=True):
interpreter.process_page(page)
fp.close()
device.close()
textstr = retstr.getvalue()
retstr.close()
return textstr

因为是在实验室服务器上写的,环境是Python2.7。从网上参考的资料,把函数写好,最后返回的是解析的pdf,截取一小段解析的结果:

效果不错,发现页码都是单独成行,这样就非常利于提取了。

再把页码提取出来,最后把一年的期刊都爬取一下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
def get_issues(iss):
url='http://www.plantcell.org/content/28/' + str(iss) + '.toc.pdf'
fp = StringIO(urlopen(url).read())
text=convert_pdf_to_txt(fp)
text = str(text).split("\n")
all = []
for i in text:
#print (i)
if re.findall('\D+', i):
pass
elif i != '' :
all.append(i)
print (all)
if __name__ == "__main__":
for iss in range(1,12):
#print (iss)
get_issues(iss)

split按回车分割text,再把text遍历,找出没有非数字出现的文本,并去除空字符,最后把每个页码添加进all列表,输出即可。

结果:

成功完成,这个获得页码的脚本就写好了,留在一边备用。

现在来解析文章的摘要等信息,回到摘要网页,查看源代码。
很简单的使用BeautifulSoup4把信息提取出来,过程就不赘述。

代码太多,不贴了,放在github上。
花了半天的时间,今天就先做到这了,之后有空再继续。

Yumin Huang wechat
快来订阅我的公众号吧-,-
坚持原创分享,来支持一下作者吧~