代码

# encoding=utf-8
import os, time, re
import urllib.request
import urllib.parse
import ssl ssl._create_default_https_context = ssl._create_unverified_context
retmax = 500
FAILURE = 0
SUCCESS = 1
startNum = 1 BASE = 'NARA'
FILES= ['Losartan','Valsartan','Irbesartan','Eprosartan','Candesartan','Telmisartan','Olmesartan'] # BASE = 'Triptans'
# FILES = ['Sumatriptan','Zolmitriptan',
# 'Naratriptan','Rizatriptan','Almotriptan',
# 'Frovatriptan','Eletriptan'] if not os.path.exists(BASE):
os.mkdir(BASE) def lastline(fd):
lastNum = 0
print(fd)
if not os.path.isfile(fd):
f_check = open(fd, 'w')
f_check.close()
f = open(fd, 'r')
lines = f.readlines()
f.close()
if lines:
lastNum = int(lines[-1].strip())
return lastNum def Download(drug, sleep_time, query_key, webenv, endNum):
lastNum = lastline('{}/{}/checkpoint.txt'.format(BASE,drug))
if lastNum == 0:
start = startNum - 1
else:
start = lastNum + retmax
# print(lastNum)
f_append = open('{}/{}/checkpoint.txt'.format(BASE, drug), 'a')
f_error = open('{}/{}/error.txt'.format(BASE, drug), 'a')
try:
for retstart in range(start, endNum, retmax):
time.sleep(sleep_time)
print('\tdownloading: %d - %d' % (retstart + 1, retstart + retmax))
urllib.request.urlretrieve('https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?'
'db=pubmed&query_key=%s&WebEnv=%s&retstart=%s&retmax=%s&retmode=xml' % (
query_key, webenv, retstart, retmax),
'%s/%s/%d-%d.xml' % (BASE, drug, retstart + 1, retstart + retmax)) f_append.write('%d\n' % (retstart))
f_append.flush()
except Exception as ex:
print(ex)
# print('\t\tbad connection!')
raise Exception()
return FAILURE
finally:
f_append.close()
f_error.close() print('Downloading is done........................')
return SUCCESS def Download_auto(fun, drug, query_key, webenv, endNum, sleep_time=5):
while True:
try:
value = fun(drug, sleep_time, query_key, webenv, endNum)
if value == SUCCESS:
break
except Exception as e:
sleep_time += 5
print('prolong sleep time:', sleep_time) def main(drug):
"""主函数"""
if not os.path.exists('{}/{}'.format(BASE,drug)):
os.mkdir('{}/{}'.format(BASE,drug))
query = '%s[TIAB]+OR+%s[MH]' % (drug, drug)
url = 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=pubmed&term={}&usehistory=y'.format(query)
history = urllib.request.urlopen(url)
content = history.read().decode()
pattern = re.compile('<Count>(\d+)</Count>.*<QueryKey>(\d+)</QueryKey>.*<WebEnv>(\S+)</WebEnv>')
s = pattern.search(content)
count = s.group(1)
query_key = s.group(2)
webenv = s.group(3)
print('total counts: %s' % count)
endNum = int(count)
print(endNum)
Download_auto(Download,drug, query_key, webenv, endNum) if __name__ == '__main__':
start = time.time()
list(map(main, FILES))
print(time.time() - start)

  

爬虫案例之Pubmed数据库下载的更多相关文章

  1. python爬虫主要就是五个模块:爬虫启动入口模块,URL管理器存放已经爬虫的URL和待爬虫URL列表,html下载器,html解析器,html输出器 同时可以掌握到urllib2的使用、bs4(BeautifulSoup)页面解析器、re正则表达式、urlparse、python基础知识回顾(set集合操作)等相关内容。

    本次python爬虫百步百科,里面详细分析了爬虫的步骤,对每一步代码都有详细的注释说明,可通过本案例掌握python爬虫的特点: 1.爬虫调度入口(crawler_main.py) # coding: ...

  2. Golang - 爬虫案例实践

    目录 Golang - 爬虫案例实践 1. 爬虫步骤 2. 正则表达式 3. 并发爬取美图 Golang - 爬虫案例实践 1. 爬虫步骤 明确目标(确定在哪个网址搜索) 爬(爬下数据) 取(去掉没用 ...

  3. Python 简单爬虫案例

    Python 简单爬虫案例 import requests url = "https://www.sogou.com/web" # 封装参数 wd = input('enter a ...

  4. Java爬虫爬取网站电影下载链接

    之前有看过一段时间爬虫,了解了爬虫的原理,以及一些实现的方法,本项目完成于半年前,一直放在那里,现在和大家分享出来. 网络爬虫简单的原理就是把程序想象成为一个小虫子,一旦进去了一个大门,这个小虫子就像 ...

  5. MySQL数据库下载安装和DataGrip的下载安装和破解

    一: 数据库下载 地址:官网https://dev.mysql.com/downloads/file/?id=482771;如果参数id失效,就选择之前的版本,5.7就可以,太新的没人用,老的很稳定. ...

  6. ASP.NET中防止Access数据库下载

    如何防止Access数据库下载是一个很老的话题了,网上的讨论也比较多.这里我们给出几种在ASP.NET下防止Access数据库被下载的方法. 我们这里假设Access数据库名字为 test.mdb. ...

  7. Python 实用爬虫-04-使用 BeautifulSoup 去水印下载 CSDN 博客图片

    Python 实用爬虫-04-使用 BeautifulSoup 去水印下载 CSDN 博客图片 其实没太大用,就是方便一些,因为现在各个平台之间的图片都不能共享,比如说在 CSDN 不能用简书的图片, ...

  8. 【Python爬虫案例学习】下载某图片网站的所有图集

    前言 其实很简短就是利用爬虫的第三方库Requests与BeautifulSoup. 其实就几行代码,但希望没有开发基础的人也能一下子看明白,所以大神请绕行. 基本环境配置 python 版本:2.7 ...

  9. java爬虫案例学习

    最近几天很无聊,学习了一下java的爬虫,写一些自己在做这个案例的过程中遇到的问题和一些体会1.学习目标         练习爬取京东的数据,图片+价格+标题等等 2.学习过程 1·开发工具      ...

随机推荐

  1. AngularJS学习之旅—AngularJS Http(九)

    1.AngularJS XMLHttpRequest $http 是 AngularJS 中的一个核心服务,用于读取远程服务器的数据. eg: // 简单的 GET 请求,可以改为 POST $htt ...

  2. MySQL 数据库的创建&修改

    -- 创建数据库 CREATE DATABASE [IF NOT EXISTS]<数据库名> DEFAULT CHARACTER SET utf8; -- 默认字符集为utf8 -- 指定 ...

  3. 《精通Spring+4.x++企业应用开发实战》读后感

    引言 还记得大三时上培训班的是时候,当时的培训老师说自己是本地讲解spring最好的讲师,但是后来等我实习了看了<Spring 3.x 企业应用开发实战>以及后续版本<精通Sprin ...

  4. 【Python 07】汇率兑换1.0-2(基本元素)

    1.Python基本元素 (1)缩进:表示代码层次关系(Python中表示程序框架唯一手段) 1个tab或者4个空格 (2)注释:开发者加入的说明信息,不被执行.一个代码块一个注释. # 单行注释(一 ...

  5. SpringBoot学习笔记(2) Spring Boot的一些配置

    外部配置 Spring Boot允许使用properties文件.yaml文件或者命令行参数作为外部配置 使用@Value注解,可以直接将属性值注入到你的beans中,并通过Spring的Enviro ...

  6. java 常用工具整理

    mapUtil map操作工具类 <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-collections4 ...

  7. linux 系统信息展示 htop glances conky psensor

    htop glances conky psensor htop glances 只能在终端内展示. htop 使用系统自带程序包管理程序就可以安装 glances github地址:https://g ...

  8. InvalidOperationException: Unable to resolve service for type 'Microsoft.AspNetCore.Identity.UserManager`1[Microsoft.AspNetCore.Identity.IdentityUser]'

    在新建asp.net core 应用后, 添加了自定义的ApplicationDbContext 和ApplicationUser ,并添加了Identity认证后, 会出现 InvalidOpera ...

  9. springboot2+freemarker简单使用

    一.src/main/resources/templates下新建welcome.ftl <!DOCTYPE html> <html lang="en"> ...

  10. 烦神的斐波那契&&洛谷-1306-斐波那契公约数

    传送门 洛谷1306传送门 -------------------------------------------------------------------------------------- ...