您的位置:首页 > 编程语言 > Python开发

使用python爬虫抓取学术论文

2015-03-25 20:19 2146 查看

介绍

这是一个很小的爬虫,可以用来爬取学术引擎的pdf论文,由于是网页内容是js生成的,所以必须动态抓取。通过selenium和chromedriver实现。可以修改起始点的URL从谷粉搜搜改到谷歌学术引擎,如果你的电脑可以翻墙。可以修改关键字 和 搜索页数 搜索需要的论文

资源下载

selenium和chromedriver,2015-3月最新版本下载地址 http://pan.baidu.com/s/1qWLqqqK

注意运行程序前 启动selenium 命令为 java -jar selenium.jar

python代码

#!/usr/bin/python
#encoding=utf-8
__author__ = 'Administrator'
from selenium import selenium

if __name__ == "__main__":
import os
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait

chromedriver = "C:\Program Files\Google\Chrome\Application\chromedriver.exe"
os.environ["webdriver.chrome.driver"] = chromedriver
driver = webdriver.Chrome(chromedriver)
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
driver.get('http://www.gfsoso.com/scholar')
inputElement = driver.find_element_by_name("q")
searchWord="sentiment lexicon"
inputElement.send_keys(searchWord)
inputElement.submit()
currentURL=driver.current_url
urlList=[]
localDir = 'down_pdf\\'
fileOut = localDir + searchWord + ".txt"
import urllib, re,codecs,sys
fileOp = codecs.open(fileOut, 'a', sys.getdefaultencoding())
for i in range(0,10):#需要抓取的页数
pdf_url = driver.find_elements_by_css_selector("a")
for k in pdf_url:
try:
z= k.get_attribute("href")
if '.pdf' in z and z not in urlList:
urlList.append(z)
print z
except:
import time
time.sleep(1)
continue
contents=driver.find_elements_by_css_selector('h3')
for ct in contents:
print ct.text
#fileOp.write('%s\n' %(ct.text))#把页面上所有的文章名称存到txt,有时会报错
driver.get(currentURL+"&start="+str(i*10)+"&as_sdt=0,5&as_ylo=2008")
import time
time.sleep(3)
print len(urlList)

for everyURL in urlList:                                  #遍历列表的每一项,即每一个PDF的url
wordItems = everyURL.split('/')                   #将url以/为界进行划分,为了提取该PDF文件名
for item in wordItems:                            #遍历每个字符串
if re.match('.*\.pdf$', item):            #查找PDF的文件名
PDFName = item                    #查找到PDF文件名
localPDF = localDir +searchWord+"_"+ PDFName
try:
urllib.urlretrieve(everyURL, localPDF)    #按照url进行下载,并以其文件名存储到本地目录
except Exception,e:
continue
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python 学术论文 爬虫