Python爬取三国演义

文/bluescorpio

爬虫四部曲:

1.从哪爬 where
2.爬什么 what
3.怎么爬 how
4.爬了之后信息如何保存 save
本文是练手程序之爬取三国演义

从哪爬

三国演义

爬什么

三国演义全文

怎么爬

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

<div id="con" class="bookyuanjiao">

只要找到这个节点,然后把内容写入到一个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 localeimpoyt sys
from lxml 
import tree 
import rereload(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 + "</body></html>" 

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

0.html的内容如下

<html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"></head><body>


今年**第六届大会PyConChina2016**,由PyChina.org发起,CPyUG/TopGeek 等社区协办,将在2016年9月10日(上海)9月23日(深圳)10月15日(北京)地举办的针对Python开发者所举办的最盛大和权威的Python相关技术会议,由PyChina社区主办,致力于推动各类Python相关的技术在互联网、企业应用等领域的研发和应用。


您可以点击[此处](http://www.huodongxing.com/go/pycon2016sh)
了解更多详情,或者扫描下图二维码:
![](http://upload-images.jianshu.io/upload_images/2851089-21548df2e0afa985.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容