Python爬取三国演义
admin
2023-07-30 21:10:47
0

爬虫四部曲:
1.从哪爬 where
2.爬什么 what
3.怎么爬 how
4.爬了之后信息如何保存 save

本文是练手程序之爬取三国演义

从哪爬

三国演义

爬什么

三国演义全文

怎么爬

在Chrome页面打开F12,就可以发现文章内容在节点

只要找到这个节点,然后把内容写入到一个html文件即可。

content = soup.find(\"div\", {\"class\": \"bookyuanjiao\", \"id\": \"con\"})

爬了之后如何保存

主要就是拿到内容,拼接到一个html文件,然后保存下来就可以了。

#!usr/bin/env  
# -*-coding:utf-8 -*-
import urllib2
import os
from bs4 import BeautifulSoup as BS
import locale
import sys
from lxml import etree
import re

reload(sys)
sys.setdefaultencoding(\'gbk\')

sub_folder = os.path.join(os.getcwd(), \"sanguoyanyi\")
if not os.path.exists(sub_folder):
    os.mkdir(sub_folder)

path = sub_folder

# customize html as head of the articles
input = open(r\'0.html\', \'r\')
head = input.read()

domain = \'http://www.shicimingju.com/book/sanguoyanyi.html\'
t = domain.find(r\'.html\')
new_domain = \'/\'.join(domain.split(\"/\")[:-2])
first_chapter_url = domain[:t] + \"/\" + str(1) + \'.html\'
print first_chapter_url

# Get url if chapter lists
req = urllib2.Request(url=domain)
resp = urllib2.urlopen(req)
html = resp.read()
soup = BS(html, \'lxml\')
chapter_list = soup.find(\"div\", {\"class\": \"bookyuanjiao\", \"id\": \"mulu\"})
sel = etree.HTML(str(chapter_list))
result = sel.xpath(\'//li/a/@href\')

for each_link in result:
    each_chapter_link = new_domain + \"/\" + each_link
    print each_chapter_link
    req = urllib2.Request(url=each_chapter_link)
    resp = urllib2.urlopen(req)
    html = resp.read()

    soup = BS(html, \'lxml\')
    content = soup.find(\"div\", {\"class\": \"bookyuanjiao\", \"id\": \"con\"})
    title = soup.title.text
    title = title.split(u\'_《三国演义》_诗词名句网\')[0]

    html = str(content)
    html = head + html + \"\"

    filename = path + \"\\\\\" + title + \".html\"
    print filename
    # write file
    output = open(filename, \'w\')
    output.write(html)
    output.close()

0.html的内容如下

相关内容

热门资讯

500 行 Python 代码... 语法分析器描述了一个句子的语法结构,用来帮助其他的应用进行推理。自然语言引入了很多意外的歧义,以我们...
定时清理删除C:\Progra... C:\Program Files (x86)下面很多scoped_dir开头的文件夹 写个批处理 定...
65536是2的几次方 计算2... 65536是2的16次方:65536=2⁶ 65536是256的2次方:65536=256 6553...
Mobi、epub格式电子书如... 在wps里全局设置里有一个文件关联,打开,勾选电子书文件选项就可以了。
scoped_dir32_70... 一台虚拟机C盘总是莫名奇妙的空间用完,导致很多软件没法再运行。经过仔细检查发现是C:\Program...
pycparser 是一个用... `pycparser` 是一个用 Python 编写的 C 语言解析器。它可以用来解析 C 代码并构...
小程序支付时提示:appid和... [Q]小程序支付时提示:appid和mch_id不匹配 [A]小程序和微信支付没有进行关联,访问“小...
微信小程序使用slider实现... 众所周知哈,微信小程序里面的音频播放是没有进度条的,但最近有个项目呢,客户要求音频要有进度条控制,所...
python绘图库Matplo... 本文简单介绍了Python绘图库Matplotlib的安装,简介如下: matplotlib是pyt...
Prometheus+Graf... 一,Prometheus概述 1,什么是Prometheus?Prometheus是最初在Sound...