spider_main.py
from 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):
self.urls.add_new_url(root_url)
count = 1
while self.urls.has_new_url():
try:
new_url = self.urls.get_new_url()
print("craw %d : %s"%(count, new_url))
html_doc = self.downloader.download(new_url)
html_data, html_url = self.parser.parse(new_url, html_doc)
self.urls.add_new_url(html_url)
self.outputer.collect_data(html_data)
count = count+1
except:
print("craw failed")
self.outputer.output_data()
if __name__ == "__main__":
root_url = "http://www.wmtxt.net/book/5446/4217938.html"
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):
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):
if self.new_urls is None:
return
else:
return self.new_urls.pop()
def add_new_urls(self, html_urls):
if html_urls is None or len(html_urls) == 0:
return
for url in html_urls:
self.new_urls.add(url)
html_downloader.py
import urllib.request
class HtmlDownloader(object):
def download(self, new_url):
return urllib.request.urlopen(new_url).read()
html_parser.py
from urllib.parse import urljoin
from bs4 import BeautifulSoup
class HtmlParser(object):
def parse(self, page_url, html_doc):
if page_url is None or html_doc is None:
return
soup = BeautifulSoup(html_doc, 'html.parser', from_encoding='utf-8')
new_url = self.get_new_url(page_url, soup)
new_data = self.get_new_data(soup)
return new_data, new_url
@staticmethod
def get_new_url(page_url, soup):
new_url = soup.find('a', id="linkNext")['href']
new_full_url = urljoin(page_url, new_url)
return new_full_url
@staticmethod
def get_new_data(soup):
res_data = ""
datas = soup.find_all('br')
for data in datas:
res_data = res_data + data.get_text()
return res_data
html_outputer.py
class HtmlOutputer(object):
def __init__(self):
self.datas = []
def collect_data(self, html_data):
if html_data is None:
return
self.datas.append(html_data)
def output_data(self):
fout = open('output.html', 'w')
fout.write("<html>")
fout.write("<body>")
for data in self.datas:
fout.write("%s" % data)
fout.write("<body>")
fout.write("</html>")
fout.close()
模仿自@慕课网@蚂蚁学