亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Python爬取三國演義的實現(xiàn)方法

オリジナル 2017-01-16 13:17:28 476
サマリー:這篇文章通過實例給大家演示了利用python如何爬取三國演義,對于學(xué)習(xí)python的朋友們來說是個不錯的實例,有需要的朋友可以參考借鑒,下面來一起看看吧。本文的爬蟲教程分為四部:     1.從哪爬 where     2.爬什么 what     3.怎么爬 how&

這篇文章通過實例給大家演示了利用python如何爬取三國演義,對于學(xué)習(xí)python的朋友們來說是個不錯的實例,有需要的朋友可以參考借鑒,下面來一起看看吧。

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

     1.從哪爬 where

     2.爬什么 what

     3.怎么爬 how

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

一、從哪爬

三國演義

二、爬什么

三國演義全文

三、怎么爬

在Chrome頁面打開F12,就可以發(fā)現(xiàn)文章內(nèi)容在節(jié)點

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

只要找到這個節(jié)點,然后把內(nèi)容寫入到一個html文件即可。

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

四、爬了之后如何保存

主要就是拿到內(nèi)容,拼接到一個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'_《三國演義》_詩詞名句網(wǎng)')[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的內(nèi)容如下

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

 更多關(guān)于Python爬取三國演義的實現(xiàn)方法請關(guān)注PHP中文網(wǎng)(ipnx.cn)其他文章!


手記を発表する

人気のある見出し語