一次简单的爬虫
目标网站:
http://www.shicimingju.com/chaxun/zuozhe/9.html,爬取苏轼的所有诗词,并存入mongoDB,步骤如下:
1、分析目标网站
2、提取目标数据,可通过正则提取出诗词的标题和诗词内容
3、将提取出的内容存到mongo
以下为全部代码:
1 import re 2 import requests 3 import datetime 4 from pymongo import MongoClient 5 6 # mongo为本地搭建的 7 def create_mongoConn(): 8 client = MongoClient('mongodb://localhost:27017/shici') 9 db = client.shici 10 return db 11 12 db = create_mongoConn() 13 coll = db.sushi 14 15 def logger(message): 16 print(str(datetime.datetime.now()) + ' ' + message) 17 logger('start') 18 # 总共173页 19 for i in range(1, 174): 20 if i == 1: 21 url = 'http://www.shicimingju.com/chaxun/zuozhe/9.html' 22 else: 23 url = 'http://www.shicimingju.com/chaxun/zuozhe/9_%s.html' % i 24 res = requests.get(url) 25 pattern1 = re.compile('<a\shref="javascript:void\(0\)"\sclass="show_more_shici".*?none">', re.S) 26 text = re.sub(pattern1, '', res.text) 27 pattern = re.compile('<div\sclass="shici_list_main">.*?《(.*?)》.*?<div\sclass="shici_content">(.*?)</div>', re.S) 28 results = re.findall(pattern, text) 29 count = 20 * (i - 1) 30 for result in results: 31 count += 1 32 poem_title = result[0].strip() 33 poem_content = result[1].replace(' ', '') 34 poem_content_temp = re.sub('<br\/>', '', poem_content) 35 poem_content_final = re.sub('<br>', '',poem_content_temp) 36 #写入文件 37 # with open(file='sushi_poem.txt', mode='a+', encoding='utf-8') as f: 38 # f.writelines(str(count) + '、'+poem_title + '\n') 39 # f.writelines(poem_content_final + '\n') 40 #写入mongo 41 coll.insert_one({'poetry_name' : poem_title, 'poetry_content' : poem_content_final, 'poet' : '苏轼'}) 42 logger('end')
其中,未解决的问题有匹配诗词标题时,多个双引号的未完全匹配,如:《子由在筠作《东轩记》,或戏之为东轩长老。》,还未解决,后续再想办法。
参考资料:
正则使用方法:https://www.py.cn/spider/guide/14488.html

浙公网安备 33010602011771号