Python实现爬虫从网络上下载文档的实例代码


Posted in Python onJune 13, 2018

最近在学习Python,自然接触到了爬虫,写了一个小型爬虫软件,从初始Url解析网页,使用正则获取待爬取链接,使用beautifulsoup解析获取文本,使用自己写的输出器可以将文本输出保存,具体代码如下:

Spider_main.py

# coding:utf8
from baike_spider import url_manager, html_downloader, html_parser, html_outputer
class SpiderMain(object):
  def __init__(self):
    self.urls = url_manager.UrlManager()
    self.downloader = html_downloader.HtmlDownloader()
    self.parser = html_parser.HtmlParser()
    self.outputer = html_outputer.HtmlOutputer()
  def craw(self, root_url):
    count = 1
    self.urls.add_new_url(root_url)
    while self.urls.has_new_url():
      print("self.urls.has %s" % self.urls.new_urls)
      try:
        new_url = self.urls.get_new_url()
        print("craw %d : %s"%(count, new_url))
        html_cont = self.downloader.download(new_url)
        new_urls, new_data = self.parser.parse(new_url, html_cont)
        self.urls.add_new_urls(new_urls)
        self.outputer.collect_data(new_data)
        if count == 1000:
          break
        count = count + 1
      except:
        print("craw failed")
    self.outputer.output_html()
    self.outputer.output_txt()
if __name__ == '__main__':
  root_url = "http://www.shushu8.com/jiangnan/longzu2qianzhuan/1"
  obj_spider = SpiderMain()
  obj_spider.craw(root_url)

url_manager.py

class UrlManager(object):
  def __init__(self):
    self.new_urls = set()
    self.old_urls = set()
  def add_new_url(self, url):
    print(url)
    if url is None:
      return
    if url not in self.new_urls and url not in self.old_urls:
      self.new_urls.add(url)
  def has_new_url(self):
    return len(self.new_urls) != 0
  def get_new_url(self):
    new_url = self.new_urls.pop()
    self.old_urls.add(new_url)
    # print('new url is %s' % new_url)
    return new_url
  def add_new_urls(self, urls):
    print("add_new_urls %s" % urls)
    if urls is None or len(urls) == 0:
      return
    for url in urls:
      self.add_new_url(url)
      print(url)

html_parser.py

import re
import urllib.parse
from bs4 import BeautifulSoup
class HtmlParser(object):
  def parse(self, page_url, html_cont):
    if page_url is None or html_cont is None:
      return
    soup = BeautifulSoup(html_cont, 'html.parser', from_encoding='utf-8')
    new_urls = self._get_new_urls(page_url, soup)
    print("parse new_urls %s" % new_urls)
    new_data = self._get_new_data(page_url, soup)
    return new_urls, new_data
  def _get_new_data(self, page_url, soup):
    res_data = {}
    res_data['url'] = page_url
    print(page_url)
    title_node = soup.find(class_="title").find("h1")
    print(title_node.get_text())
    res_data['title'] = title_node.get_text()
    print("_get_new_data")
    summary_node = soup.find('pre')
    print(summary_node.get_text())
    res_data['summary'] = summary_node.get_text()
    return res_data
  def _get_new_urls(self, page_url, soup):
    new_urls = set()
    links = soup.find_all('a', href=re.compile(r"/jiangnan/"))
    print(links)
    for link in links:
      new_url = link['href']
      new_full_url = urllib.parse.urljoin(page_url, new_url)
      new_urls.add(new_full_url)
      # print(new_full_url)
    return new_urls

html_downloader.py

import urllib.request
class HtmlDownloader(object):
  def download(self, url):
    if url is None:
      return None
    response = urllib.request.urlopen(url)
    if response.getcode() != 200:
      return None
    return response.read()

html_outputer.py

class HtmlOutputer(object):
  def __init__(self):
    self.datas = []
  def collect_data(self, data):
    if data is None:
      return
    self.datas.append(data)
  def output_txt(self):
    fout = open('output.txt', 'w', encoding='utf-8')
    for data in self.datas:
      fout.write('%s \n' % data['title'])
      fout.write('%s \n' % data['summary'])
  def output_html(self):
    fout = open('output.html', 'w', encoding='utf-8')
    fout.write('<html>')
    fout.write('<body>')
    fout.write('<table>')
    for data in self.datas:
      fout.write('<tr>')
      fout.write('<td>%s</td>' % data['url'])
      fout.write('<td>%s</td>' % data['title'])
      fout.write('<td>%s</td>' % data['summary'])
      fout.write('</tr>')
    fout.write('</table>')
    fout.write('</body>')
    fout.write('</html>')
    fout.close()

总结

以上所述是小编给大家介绍的Python实现爬虫从网络上下载文档的实例代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对三水点靠木网站的支持!

Python 相关文章推荐
解决python写的windows服务不能启动的问题
Apr 15 Python
Python自动化测试ConfigParser模块读写配置文件
Aug 15 Python
Python向日志输出中添加上下文信息
May 24 Python
python实现微信防撤回神器
Apr 29 Python
如何用Python做一个微信机器人自动拉群
Jul 03 Python
Python对接六大主流数据库(只需三步)
Jul 31 Python
Pandas时间序列基础详解(转换,索引,切片)
Feb 26 Python
Django 自定义权限管理系统详解(通过中间件认证)
Mar 11 Python
Python中的__init__作用是什么
Jun 09 Python
Keras - GPU ID 和显存占用设定步骤
Jun 22 Python
使用Python实现NBA球员数据查询小程序功能
Nov 09 Python
Python调用Redis的示例代码
Nov 24 Python
Pycharm导入Python包,模块的图文教程
Jun 13 #Python
mac下pycharm设置python版本的图文教程
Jun 13 #Python
使用Python来开发微信功能
Jun 13 #Python
python爬取足球直播吧五大联赛积分榜
Jun 13 #Python
Python实现多条件筛选目标数据功能【测试可用】
Jun 13 #Python
mac 安装python网络请求包requests方法
Jun 13 #Python
Scrapy基于selenium结合爬取淘宝的实例讲解
Jun 13 #Python
You might like
在php中取得image按钮传递的name值
2006/10/09 PHP
PHP通过COM使用ADODB的简单例子
2006/12/31 PHP
php下网站防IP攻击代码,超级实用
2010/10/24 PHP
CI框架学习笔记(二) -入口文件index.php
2014/10/27 PHP
PHP调用Mailgun发送邮件的方法
2017/05/04 PHP
php格式文件打开的四种方法
2018/02/24 PHP
PHP批斗大会之缺失的异常详解
2019/07/09 PHP
jquery1.4 教程二 ajax方法的改进
2010/02/25 Javascript
jQuery中add实现同时选择两个id对象
2010/10/22 Javascript
javascript各浏览器中option元素的表现差异
2011/04/07 Javascript
使用JavaScript动态设置样式实现代码及演示动画
2013/01/25 Javascript
js采用map取到id集合组并且实现点击一行选中一行
2013/12/16 Javascript
jQuery过滤选择器:not()方法使用介绍
2014/04/20 Javascript
node.js中的fs.link方法使用说明
2014/12/15 Javascript
异步安全加载javascript文件的方法
2015/07/21 Javascript
JQuery validate插件Remote用法大全
2016/05/15 Javascript
web前端开发upload上传头像js示例代码
2016/10/22 Javascript
Vue(定时器)解决mounted不能获取到data中的数据问题
2020/07/30 Javascript
Python使用requests及BeautifulSoup构建爬虫实例代码
2018/01/24 Python
python 删除非空文件夹的实例
2018/04/26 Python
python利用Tesseract识别验证码的方法示例
2019/01/21 Python
使用Python画出小人发射爱心的代码
2019/11/23 Python
解决tensorflow由于未初始化变量而导致的错误问题
2020/01/06 Python
Python使用tkinter实现摇骰子小游戏功能的代码
2020/07/02 Python
Python实现异步IO的示例
2020/11/05 Python
解决TensorFlow训练模型及保存数量限制的问题
2021/03/03 Python
HTML5 Canvas实现文本对齐的方法总结
2016/03/24 HTML / CSS
香港士多网上超级市场:Ztore
2021/01/09 全球购物
怎么样写好简历中的自我评价
2013/10/25 职场文书
创业计划书怎样才能打动风投
2014/01/01 职场文书
收银员岗位职责
2014/02/07 职场文书
幼儿教师工作感言
2014/02/14 职场文书
大学生励志演讲稿
2014/04/25 职场文书
2014年客房部工作总结
2014/11/22 职场文书
MySQL update set 和 and的区别
2021/05/08 MySQL
MySQL中的隐藏列的具体查看
2021/09/04 MySQL