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

Python爬取三国演义的实现方法,第1张

概述本文的爬虫教程分为四部:    1.从哪爬where    2.爬什么what

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

     1.从哪爬 where

     2.爬什么 what

     3.怎么爬 how

     4.爬了之后信息如何保存 save

一、从哪爬

三国演义

二、爬什么

三国演义全文

三、怎么爬

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

<div ID="con" >

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

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

四、爬了之后如何保存

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

#!usr/bin/env # -*-Coding:utf-8 -*-import urllib2import osfrom bs4 import BeautifulSoup as BSimport localeimport sysfrom lxml import etreeimport 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 articlesinput = 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 Listsreq = urllib2.Request(url=domain)resp = urllib2.urlopen(req)HTML = resp.read()soup = BS(HTML,'lxml')chapter_List = soup.find("div","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","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爬取三国演义的实现方法全部内容,希望文章能够帮你解决Python爬取三国演义的实现方法所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1203666.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-04
下一篇 2022-06-04

发表评论

登录后才能评论

评论列表(0条)

保存