一、文章简介
教程视频:http://www.imooc.com/learn/563
基于慕课网教程的开发,不同之处在于本人使用Python3进行的开发,本篇文章主要有两个内容:
1.讲述编码过程中与视频教程中的不同点
2.基于教程的源码(根据python3修改)
3.效果图
二、具体内容
1.python2与python的不同(以下将两版本简称为2,和3)
①urlopen的引用方式不同:在2中利用urllib模块直接引用urlopen方法打开,在3中利用urllib模块中的request对象的urlopen方法打开
详情(摘自:http://blog.csdn.net/chen1540524015/article/details/73717948):
urllib库是python提供的一个用于操作URL的模块,在python2中有urllib和urllib2,在python3中urllib2合并到urllib中,区别和联系如下:
1) 在python2中使用的import urllib2——对应的,在python3中使用import urllib.request , import urllib.error
2) 在python2中使用的import urllib——对应的,在python3中使用import urllib.request , import urllib.error,import urllib.parse
3) 在python2中使用的import urlparse——对应的,在python3中使用import urllib.parse
4) 在python2中使用的import urllib2.urlopen——对应的,在python3中使用import urllib.request.urlopen
5) 在python2中使用的import urllib.urlencode——对应的,在python3中使用import urllib.parse.urlencode
6) 在python2中使用的import urllib.quote——对应的,在python3中使用import urllib.request.quote
7) 在python2中使用的import cookielib.CookieJar——对应的,在python3中使用import http.CookieJar
8) 在python2中使用的import urllib2.Request——对应的,在python3中使用import urllib.request.Reques②编码错误一:输出文本格式
Windows下自动保存文本格式为gbk,因此在
open('output.html', 'w') 应改为 open('output.html', 'w', encoding='utf-8')
问题可详见:
<a href="http://www.jb51.net/article/64816.htm">Python UnicodeEncodeError: 'gbk' codec can't encode character 解决方法</a>
③编码错误二:编/解码问题
3中会自动将网页中的编码转为utf8的格式不需要再次编码
例如:
fout.write("<td>%s</td>" % data['title'].encode('utf8')) 不需要encode编码
fout.write("<td>%s</td>" % data['title'])
④编码错误三:URL中汉字解码方式
详见不同点①详情部分,引用3中的parse对象的unquote方法对爬取数据的URL进行解析,代码如下:
urllib.parse.unquote(data['url'])
2.源码
①爬虫主函数 spider_main:
# coding:utf8
# 设置文本格式
'''
Created on 2017年11月2日
@author: zrq
'''
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.HtmlDownloder()
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():
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 == 100:
break
count = count + 1
except:
print('craw failed')
self.outputer.output_html()
if __name__ == "__main__":
root_url = "https://baike.baidu.com/item/Python/407313.html"
obj_spider = SpiderMain()
obj_spider.craw(root_url)
②url管理器 url_manager :
# coding:utf8
# 设置文本格式
'''
Created on 2017年11月2日
@author: zrq
'''
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 add_new_urls(self, urls):
if urls is None or len(urls) == 0:
return
for url in urls:
self.add_new_url(url)
def has_new_url(self):
return len(self.new_urls) != 0
def get_new_url(self):
new_url = self.new_urls.pop() # 获取并移除url
self.old_urls.add(new_url)
return new_url
③网页解析器 html_parser :
# coding:utf8
# 设置文本格式
'''
Created on 2017年11月2日
@author: zrq
'''
from bs4 import BeautifulSoup
import re
from urllib.parse import urljoin
class HtmlParser(object):
def _get_new_urls(self, page_url, soup):
new_urls = set()
# /item/*
links = soup.find_all('a', href=re.compile(r"/item/*"))
for link in links:
new_url = link['href']
new_full_url = urljoin(page_url, new_url)
new_urls.add(new_full_url)
return new_urls
def _get_new_data(self, page_url, soup):
res_data = {}
# url
res_data['url'] = page_url
#<dd class="lemmaWgt-lemmaTitle-title"><h1>Python</h1>
title_node = soup.find(
'dd', class_="lemmaWgt-lemmaTitle-title").find("h1")
res_data['title'] = title_node.get_text()
#<div class="lemma-summary" label-module="lemmaSummary">
summary_node = soup.find('div', class_="lemma-summary")
res_data['summary'] = summary_node.get_text()
return res_data
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)
new_data = self._get_new_data(page_url, soup)
return new_urls, new_data
④网页下载器 html_downloader :
# coding:utf8
# 设置文本格式
'''
Created on 2017年11月2日
@author: zrq
'''
from urllib import request
class HtmlDownloder(object):
def download(self, url):
if url is None:
return None
response = request.urlopen(url)
if response.getcode() != 200:
return None
return response.read()
⑤文本输出 html_outputer :
# coding:utf8
# 设置文本格式
'''
Created on 2017年11月2日
@author: zrq
'''
import urllib
class HtmlOutputer(object):
def __init__(self):
self.datas = []
def collect_data(self, data):
if data is None:
return
self.datas.append(data)
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>" % urllib.parse.unquote(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()
3.运行效果图
爬取页面:
爬取时控制台输出:
爬取输出结果: