最近在学习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实现爬虫从网络上下载文档的更多相关文章

  1. Python小爬虫-自动下载三亿文库文档

    新手学python,写了一个抓取网页后自动下载文档的脚本,和大家分享. 首先我们打开三亿文库下载栏目的网址,比如专业资料(IT/计算机/互联网)http://3y.uu456.com/bl-197?o ...

  2. python Cmd实例之网络爬虫应用

    python Cmd实例之网络爬虫应用 标签(空格分隔): python Cmd 爬虫 废话少说,直接上代码 # encoding=utf-8 import os import multiproces ...

  3. 使用Python爬虫库BeautifulSoup遍历文档树并对标签进行操作详解(新手必学)

    为大家介绍下Python爬虫库BeautifulSoup遍历文档树并对标签进行操作的详细方法与函数下面就是使用Python爬虫库BeautifulSoup对文档树进行遍历并对标签进行操作的实例,都是最 ...

  4. 第三百六十二节,Python分布式爬虫打造搜索引擎Scrapy精讲—elasticsearch(搜索引擎)基本的索引和文档CRUD操作、增、删、改、查

    第三百六十二节,Python分布式爬虫打造搜索引擎Scrapy精讲—elasticsearch(搜索引擎)基本的索引和文档CRUD操作.增.删.改.查 elasticsearch(搜索引擎)基本的索引 ...

  5. 四十一 Python分布式爬虫打造搜索引擎Scrapy精讲—elasticsearch(搜索引擎)基本的索引和文档CRUD操作、增、删、改、查

    elasticsearch(搜索引擎)基本的索引和文档CRUD操作 也就是基本的索引和文档.增.删.改.查.操作 注意:以下操作都是在kibana里操作的 elasticsearch(搜索引擎)都是基 ...

  6. Python 网页爬虫 & 文本处理 & 科学计算 & 机器学习 & 数据挖掘兵器谱(转)

    原文:http://www.52nlp.cn/python-网页爬虫-文本处理-科学计算-机器学习-数据挖掘 曾经因为NLTK的缘故开始学习Python,之后渐渐成为我工作中的第一辅助脚本语言,虽然开 ...

  7. Python开发爬虫之理论篇

    爬虫简介 爬虫:一段自动抓取互联网信息的程序. 什么意思呢? 互联网是由各种各样的网页组成.每一个网页对应一个URL,而URL的页面上又有很多指向其他页面的URL.这种URL之间相互的指向关系就形成了 ...

  8. 【Python】Python 网页爬虫 & 文本处理 & 科学计算 & 机器学习 & 数据挖掘兵器谱

    本文转载自:https://www.cnblogs.com/colipso/p/4284510.html 好文 mark http://www.52nlp.cn/python-%E7%BD%91%E9 ...

  9. 最全数据分析资料汇总(含python、爬虫、数据库、大数据、tableau、统计学等)

    一.Python基础 Python简明教程(Python3) Python3.7.4官方中文文档 Python标准库中文版 廖雪峰 Python 3 中文教程 Python 3.3 官方教程中文版 P ...

随机推荐

  1. hibernate事务管理 (jdbc jta)

    hibernate的两种事务管理jdbc 和jta方式.下边说说两者的区别一.说明一下jdbc和jta方式事务管理的区别:JDBC事务由Connnection管理,也就是说,事务管理实际上是在JDBC ...

  2. Maven学习篇一:依赖了解

    1.依赖配置 <project> ... <dependencies> <dependency> <groupId>xx</groupId> ...

  3. CSS深入理解学习笔记之border

    1.border-width border-width为何不支持百分比:语义和使用场景决定的,现实中各种边框本身的概念就不存在百分比的使用方法. border-width支持关键字:thin.medi ...

  4. Android 软键盘弹出,界面整体上移

    在做搜索功能的时候,点击搜索框,搜索框获取焦点,键盘弹出:现在问题出来了,android软键盘弹出的时候,android整个界面上移,布局被挤压,很难看:要解决这个问题,我们需要用到 windowSo ...

  5. 如何设置树莓派的VNC开机时启动

    转载:http://www.linuxidc.com/Linux/2016-12/138793.htm 下面正式开始配置 首先 sudo nano /etc/init.d/vncserver 然后 复 ...

  6. php导出cvs xls xlsx

    有两种方法,一种是更改输出头部,一种是使用phpexcel类,很显然前者更方便,下面给出一个demo方法导出cvs/** * 导出日志 */public function excel() { setl ...

  7. NO.010-2018.02.15《上邪》两汉:佚名

    上邪_古诗文网 上邪 两汉:佚名 上邪,我欲与君相知,长命无绝衰.上天呀!我渴望与你相知相惜,长存此心永不褪减.上邪(yé)!:天啊!.上,指天.邪,语气助词,表示感叹. 相知:相爱.命:古与“令”字 ...

  8. linux下安装jdk和配置环境变量

    参考博文:http://www.cnblogs.com/samcn/archive/2011/03/16/1986248.html 系统环境:linux centos 6.4_x64 软件版本:jdk ...

  9. mongorc.js文件

    当启动的时候,mongo检查用户HOME目录下的一个JavaScript文件.mongorc.js.如果找到,mongo在首次显示提示信息前解析.mongorc.js的内容.如果你使用shell执行一 ...

  10. Android——Intent,Bundle

    Intent——切换activity intent.setClass(first.this,second.class); startActivity(intent); Bundle——切换时数据传递 ...