Python爬取三国演义的实现方法

yipeiwu_com5年前Python爬虫

本文的爬虫教程分为四部:

     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 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 + "</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>

总结

以上就是利用Python爬取三国演义的实现方法,希望对大家学习python能有所帮助,如果有疑问大家可以留言交流。

相关文章

Python爬虫之urllib基础用法教程

综述 本系列文档用于对Python爬虫技术进行简单的教程讲解,巩固自己技术知识的同时,万一一不小心又正好对你有用那就更好了。 Python 版本是3.7.4 urllib库介绍 它是...

Python爬虫beautifulsoup4常用的解析方法总结

摘要 如何用beautifulsoup4解析各种情况的网页 beautifulsoup4的使用 关于beautifulsoup4,官网已经讲的很详细了,我这里就把一些常用的解析方...

python批量爬取下载抖音视频

python批量爬取下载抖音视频

本文实例为大家分享了python批量爬取下载抖音视频的具体代码,供大家参考,具体内容如下 import os import requests import re import sys...

python利用selenium进行浏览器爬虫

python利用selenium进行浏览器爬虫

前言 相信大家刚开始在做爬虫的时候,是不是requests和sound这两个库来使用,这样确实有助于我们学习爬虫的知识点,下面来介绍一个算事较复杂的爬虫案例selenium进形打开浏览器...

Python3实现爬取简书首页文章标题和文章链接的方法【测试可用】

Python3实现爬取简书首页文章标题和文章链接的方法【测试可用】

本文实例讲述了Python3实现爬取简书首页文章标题和文章链接的方法。分享给大家供大家参考,具体如下: from urllib import request from bs4 imp...