国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python爬取三國演義的實現方法

2019-11-25 16:34:15
字體:
來源:轉載
供稿:網友

本文的爬蟲教程分為四部:

     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 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", {"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 + "http://" + 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能有所幫助,如果有疑問大家可以留言交流。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 嘉峪关市| 盐亭县| 乐至县| 襄樊市| 沙河市| 乳山市| 平泉县| 禹城市| 阿瓦提县| 淅川县| 永登县| 富川| 兴隆县| 行唐县| 泊头市| 临高县| 什邡市| 信宜市| 德清县| 灵丘县| 南澳县| 阿拉善左旗| 德钦县| 安吉县| 永和县| 应用必备| 惠水县| 安徽省| 乌海市| 青浦区| 普安县| 六盘水市| 中宁县| 桃江县| 鄱阳县| 鹤峰县| 津市市| 康乐县| 揭阳市| 凤城市| 德兴市|