最近在做AI作诗的项目,需要训练古诗生成模型,于是自己写了个爬虫获取古诗数据

# -*- coding:utf-8 -*-
from bs4 import BeautifulSoup
from selenium import webdriver
import time
import xlwt
import re
import string
from urllib import request
from chardet import detect
import chardet
import numpy as np
import json
from os.path import join as pjoin
import os
import time
index = 0#数据集
poet = 0#诗人的序号
def getSoup(url):# """获取源码"""fp = request.urlopen(url)content = fp.read()fp.close()type(content)html = content.decode()  # 解码det = chardet.detect(content)  # 判断content的编码方式if det['confidence'] > 0.8:  # 当confidence>0.8时认定为判断正确html = content.decode(det['encoding'])else:html = content.decode('gbk')soup = BeautifulSoup(html)return soup
#下一页
def nextUrl(soup):# """获取下一页连接后缀"""a = soup.find('a', text=re.compile("^下一页"))if a:return a.attrs['href']else:return None
#一级页面【诗人列表】
def firstPage():start = time.clock()print("开始时间:",start)page = 1#页码nt = '/shiren/index.html'global poetwhile nt:print('------------------第'+str(page)+'页-------------')soup = getSoup('https://www.gushimi.org' + nt)ol = soup.findAll('div', attrs={"class": 'news_title'})for div in ol:print(str(poet)+":" + div.a.text)poet = poet +1secondPageUrl = 'https://www.gushimi.org'+div.a.attrs['href']secondPage(secondPageUrl)print('------------------此诗人爬取结束-------------')nt = nextUrl(soup)page = page + 1end = time.clock()print("结束时间:",end)print("总共用时:", end - start)
#二级页面【某诗人诗词列表】
def secondPage(url):soup = getSoup(url)ol = soup.findAll('div', attrs={"class": "content_box"})for li in ol[2].findAll("li"):thirdPageUrl = 'https://www.gushimi.org'+li.select('a')[0].attrs['href']thirdPage(thirdPageUrl)
#三级页面【诗词详细列表】
def thirdPage(url):global indexsoup = getSoup(url)str0 = soup.findAll('div', attrs={"class": "box_title"})str0 = str0[1].text#标题ol = soup.findAll('div', attrs={"class": "news_content"})str1 = ol[0].find_all("div", class_="old_h1")[0].select('a')[0].text#朝代str2 = ol[0].find_all("div", class_="old_h1")[0].select('a')[1].text#作者print("      "+str(index)+str2+":"+str0)contents = ol[0].find_all("div", class_="newstext")[0]str3 = []#诗文for li in contents.find_all("div"):str3.append(li.text)flags = ol[0].findAll("div", class_="newstext")[1]str4 = []#关键字for li in flags.find_all("a"):str4.append(li.text)jsonData = {'index': index, 'title': str0, 'dynasty': str1, 'author': str2, 'paragraphs': str3, 'key': str4}index = index+1write_in_json_data(jsonData)
#写入json文件
def write_in_json_data(jsonData):with open('result.json', 'a', encoding='utf-8') as f:json.dump(jsonData, f, ensure_ascii=False, indent=4)if __name__ == '__main__':firstPage()

python100行代码爬取古诗相关推荐

  1. pyquery获取不到网页完整源代码_爬虫神器之PyQuery实用教程(二),50行代码爬取穷游网...

    爬虫神器之PyQuery实用教程(二),50行代码爬取穷游网 前言 上篇文章 PyQuery (一) 回顾.今天来介绍具体 PyQuery 的使用方法. 穷游网目标与分析 开始之前,按照之前的套路一步 ...

  2. Python爬虫利用18行代码爬取虎牙上百张小姐姐图片

    Python爬虫利用18行代码爬取虎牙上百张小姐姐图片 下面开始上代码 需要用到的库 import request #页面请求 import time #用于时间延迟 import re #正则表达式 ...

  3. python爬上市公司信息_实战项目 1:5 行代码爬取国内所有上市公司信息

    实战项目 1:5 行代码爬取国内所有上市公司信息 Python入门爬虫与数据分析 在正式开始这门专栏课的学习之前,我们先来看一个简单的爬虫案例.兴趣是最好的老师,当你对爬虫产生兴趣的时候,才会更有动力 ...

  4. 简单20行代码爬取王者荣耀官网1080p壁纸

    简单20行代码爬取王者荣耀官网1080p壁纸 # -*- coding: utf-8 -*- # @Time : 2020/12/13 18:08 # @Author : ningfangcong i ...

  5. Python25行代码爬取豆瓣排行榜数据

    Python25行代码爬取豆瓣排行榜数据 只需要用到requests, re ,csv 三个库即可. code import re import requests import csv url = ' ...

  6. python:利用20行代码爬取网络小说

    文章目录 前言 一.爬虫是什么? 二.实现过程 总结 提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档 前言 今天,来给大家一个分享一下如何使用20爬虫行代码爬取网络小说(这里我们以龙 ...

  7. python59行代码爬取免费ppt模板

    Python59行代码爬取某站中秋节ppt模板 网址:https://www.1ppt.com/moban/zhongqiujie/ 用到的库:requests.re.os.lxml 请求方式:GET ...

  8. 教你用python实现34行代码爬取东方财富网信息,爬虫之路,永无止境!!

    教你用python实现34行代码爬取东方财富网信息,爬虫之路,永无止境!! 代码展示: 开发环境: windows10 python3.6 开发工具: pycharm weddriver 库: sel ...

  9. python pyquery不规则数据的抓取_爬虫神器之PyQuery实用教程(二),50行代码爬取穷游网...

    爬虫神器之PyQuery实用教程(二),50行代码爬取穷游网 前言 上篇文章 PyQuery (一) 回顾.今天来介绍具体 PyQuery 的使用方法. 穷游网目标与分析 开始之前,按照之前的套路一步 ...

最新文章

  1. 一个小程序看流的读取
  2. Discuz!NT 和网站整合
  3. Spring启动教程
  4. android导入项目出现style错误,menu错误
  5. jsp中String path = request.getContextPath()的作用
  6. linux webshell 页面管理,instantbox:30s内快速搭建可通过webshell管理的Linux系统
  7. WPF Logical Tree vs. Visual Tree
  8. 【WiFi密码破解详细图文教程】ZOL仅此一份 详细介绍从CDlinux U盘启动到设置扫描破解-破解软件论坛-ZOL中关村在线...
  9. 大数据Hadoop学习(一)入门
  10. python 移动文件 使用os.rename
  11. 搭建ftp服务器的超详细步骤。
  12. 用友NC单据模板公式
  13. 软考高级系统架构设计师:五大类安全服务
  14. smbd配置windows访问linux centos的共享文件
  15. mysql 1033 frm_修复mysqldump Incorrect information in file frm (1033)
  16. DUL Oracle Data Unloader工具下载
  17. ecshop首页幻灯片大小设置
  18. 你嗑的瓜子要涨价啦?域名你“嗑”懂了吗?
  19. 嵌入式linux矩阵键盘,嵌入式linux matrix_keypad矩阵键盘驱动
  20. python代码编译出现SyntaxError: Non-ASCII character ‘\xe8‘ in file问题

热门文章

  1. vue自定义组件实现文件列表预览与下载
  2. 2016 ACOUG ASIA TOUR | 8月启程,东北三城技术联动
  3. 【Linux】按照大小、行数切割文件
  4. 卷积物理意义 卷积最简单解释
  5. 通过前缀树的敏感词过滤算法
  6. iphone 相机拍摄比例_如何在iPhone上拍摄RAW照片
  7. fastapi python 并发_如何评价最近爆红的FastAPI?
  8. (一)ORB-SLAM3 中 orb 特征提取匹配部分详解
  9. cmd命令 从C盘转到D盘
  10. JAVA计算机毕业设计ipq管理系统Mybatis+系统+数据库+调试部署