本文实例讲述了python实现爬虫抓取小说功能。分享给大家供大家参考,具体如下:

# -*- coding: utf-8 -*-
from bs4 import BeautifulSoup
from urllib import request
import re
import os,time
#访问url,返回html页面
def get_html(url):
  req = request.Request(url)
  req.add_header('User-Agent','Mozilla/5.0')
  response = request.urlopen(url)
  html = response.read()
  return html
#从列表页获取小说书名和链接
def get_books(url):#根据列表页,返回此页的{书名:链接}的字典
  html = get_html(url)
  soup = BeautifulSoup(html,'lxml')
  fixed_html = soup.prettify()
  books = soup.find_all('div',attrs={'class':'bbox'})
  book_dict = {}
  for book in books:
    book_name = book.h3.a.string
    book_url = book.h3.a.get('href')
    book_dict[book_name] = book_url
  return book_dict
#根据书名链接,获取具体的章节{名称:链接} 的字典
def get_parts(url):
  html = get_html(url)
  soup = BeautifulSoup(html,'lxml')
  fixed_html = soup.prettify()
  part_urls = soup.find_all('a')
  host = "http://www.xiaoshuotxt.org"
  part_dict = {}
  for p in part_urls:
    p_url = str(p.get('href'))
    if re.search(r'\d{5}.html',p_url) and ("xiaoshuotxt" not in p_url):
      part_dict[p.string] = host + p_url
  return part_dict
#根据章节的url获取具体的章节内容
def get_txt(url):
  html = get_html(url)
  soup = BeautifulSoup(html,'lxml')
  fixed_html = soup.prettify()
  title = soup.h1.string #获取文章标题
  content = soup.find('div',attrs={'class':'zw'})
  txt = BeautifulSoup.get_text(content) #正文内容
  return txt
if __name__ == "__main__":
  root_dir= r'e:\books'
  #url = 'http://www.xiaoshuotxt.org/mingzhu/index_2.html' #第2页的小说
  url = "http://www.xiaoshuotxt.org/writer/58" #金庸的小说
  books = get_books(url)
  for book_name,book_url in books.items():
    os.mkdir(os.path.join(root_dir,book_name))
    part_dict = get_parts(book_url)
    print(book_name,"共:",len(part_dict),"章节")
    for part_name,part_url in part_dict.items():
      print("正在保存:",part_name)
      f1 = open(r'e:\books\%s\%s.txt'%(book_name,part_name),'w',encoding='utf-8')#以utf-8编码创建文件
      part_txt = get_txt(part_url)
      f1.write(str(part_txt))
      f1.close()
      time.sleep(2)

运行效果:

python实现爬虫抓取小说功能示例【抓取金庸小说】

更多关于Python相关内容可查看本站专题:《Python Socket编程技巧总结》、《Python正则表达式用法总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总》

希望本文所述对大家Python程序设计有所帮助。

风云阁资源网 Design By www.bgabc.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
风云阁资源网 Design By www.bgabc.com

《魔兽世界》大逃杀!60人新游玩模式《强袭风暴》3月21日上线

暴雪近日发布了《魔兽世界》10.2.6 更新内容,新游玩模式《强袭风暴》即将于3月21 日在亚服上线,届时玩家将前往阿拉希高地展开一场 60 人大逃杀对战。

艾泽拉斯的冒险者已经征服了艾泽拉斯的大地及遥远的彼岸。他们在对抗世界上最致命的敌人时展现出过人的手腕,并且成功阻止终结宇宙等级的威胁。当他们在为即将于《魔兽世界》资料片《地心之战》中来袭的萨拉塔斯势力做战斗准备时,他们还需要在熟悉的阿拉希高地面对一个全新的敌人──那就是彼此。在《巨龙崛起》10.2.6 更新的《强袭风暴》中,玩家将会进入一个全新的海盗主题大逃杀式限时活动,其中包含极高的风险和史诗级的奖励。

《强袭风暴》不是普通的战场,作为一个独立于主游戏之外的活动,玩家可以用大逃杀的风格来体验《魔兽世界》,不分职业、不分装备(除了你在赛局中捡到的),光是技巧和战略的强弱之分就能决定出谁才是能坚持到最后的赢家。本次活动将会开放单人和双人模式,玩家在加入海盗主题的预赛大厅区域前,可以从强袭风暴角色画面新增好友。游玩游戏将可以累计名望轨迹,《巨龙崛起》和《魔兽世界:巫妖王之怒 经典版》的玩家都可以获得奖励。