最近在学习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. [LeetCode]27. Remove Element移除元素

    Given an array nums and a value val, remove all instances of that value in-place and return the new ...

  2. PHP file_put_contents() 函数

    file_put_contents() 函数把一个字符串写入文件中. 与依次调用 fopen(),fwrite() 以及 fclose() 功能一样. 语法如下 file_put_contents(f ...

  3. js之方法

    原文 在一个对象中绑定函数,称为这个对象的方法. 在JavaScript中,对象的定义是这样的: var xiaoming = { name: '小明', birth: 1990 }; 但是,如果我们 ...

  4. 天气小雨, 心情多云, 练习标准的键盘ABC打法

    今天看到饿了么转型生活做千亿美元公司 突然想到一些就写下来 当时外卖一份8元 10元的年代那个开心啊 很久以前宁可跑个远, 都不愿意叫外卖 叫了大概1年的外卖了, 之前还感到便宜多样, 现在感觉到的是 ...

  5. synchronized修饰普通方法和静态方法

    首先,要知道,synchronized关键字修饰普通方法时,获得的锁是对象锁,也就是this.而修饰静态方法时,锁是类锁,也就是类名.class. synchronized修饰普通方法 Synchro ...

  6. express 请求跨域后端解决方法CORS

    CORS全称Cross-Origin Resource Sharing,是HTML5规范定义的如何跨域访问资源. Origin表示本域,也就是浏览器当前页面的域.当JavaScript向外域(如sin ...

  7. DOM 和 BOM

    DOM 和  BOM DOM: DOM= Document Object Model,文档对象模型,DOM可以以一种独立于平台和语言的方式访问和修改一个文档的内容和结构.换句话说,这是表示和处理一个H ...

  8. VMware 安装提示缺少MicrosoftRuntime DLL 问题解决办法

    VMware 安装提示缺少MicrosoftRuntime DLL 问题解决办法 刚刚安装VMware失败了试了好多办法,在这总结一下. 下面是程序的截图 这是报错信息 网上的解决方法: 当出现安装失 ...

  9. react里面stateless函数的默认参数

    function fn({  children,  params,  dispatch,  location}) { }

  10. linux c开发: 在程序退出时进行处理

    有时候,希望程序退出时能进行一些处理,比如保存状态,释放一些资源.c语言开发的linux程序,有可能正常退出(exit),有可能异常crash,而异常crash可能是响应了某信号的默认处理.这里总结一 ...