018/07/09 23:43
项目名称:爬取中科院871个院士的简介信息
1.爬取目的:中科院871个院士的简介信息
2.爬取最终结果:
3.具体代码如下:
1 import re # 不用安装(注意!!) 2 import os # 文件夹等的操作(注意!!) 3 import time 4 import requests # http urllib2 5 6 url = 'http://www.cae.cn/cae/html/main/col48/column_48_1.html' 7 html = requests.get(url) 8 # print(html.status_code) # 状态码200 404 500 502 9 html.encoding = 'utf-8' 10 # print(html.text) # 以文本形式返回网页 11 12 # 提取数据 13 # + 一次或多次 大于等于一次 14 # findall返回的是列表(注意!!) 15 number = re.findall( 16 '<a href="/cae/html/main/colys/(\d+).html" target="_blank">', html.text) 17 18 i = 1 # 这里的i变量是由我创造进行明确区分所抓取的院士的数量的; 19 for m in number[:871]: 20 # for m in number[:4]: # 这里控制要爬取的个数 21 # for m in number[28:88]: 22 nextUrl = 'http://www.cae.cn/cae/html/main/colys/{}.html'.format(m) 23 # 再次请求数据 24 nexthtml = requests.get(nextUrl) 25 nexthtml.encoding = 'utf-8' 26 # 注意正则表达式: 27 # () 提取数据 28 # . 匹配除了换行\n的任意单个字符 29 # * 匹配前面的表达式任意次 {1,5} 30 # ? 如果前面有限定符 非贪婪模式,注意!!! 31 # 尽量可能少的匹配所搜索的字符串 32 text = re.findall('<div class="intro">(.*?)</div>', nexthtml.text, re.S) # re.S匹配换行的 33 text2 = re.sub(r'<p>| | |</p>', '', text[0]).strip() # .strip()清楚空格 34 35 # 保存数据 36 with open(r'E:\02中科院院士信息爬取结果.txt', mode='a+', encoding="utf-8") as f: # 特别注意这里的要以编码utf-8方式打开 37 f.write('{}. '.format(i) + text2 + '\n') 38 i += 1 39 40 # 不要下载太快 41 # 限制下载的速度 42 time.sleep(1) 43 # 程序运行到这个地方 暂停1s