抓取策略
spider_main.py# coding:utf-8
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():
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 == 10:
break
count = count + 1
except:
print(‘craw failed’)
self.outputer.output_html()
if __name__==’__main__’:
root_url = ‘http://baike.baidu.com/view/21087.htm’
obj_spider = spidermain()
obj_spider.craw(root_url)url_manger.py# coding:utf-8
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()
self.old_urls.add(new_url)
return new_urlhtml_downloader.py# coding:utf-8
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_parser.py# coding:utf-8
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()
# /view/123.htm
links = soup.find_all(‘a’, href=re.compile(r’/view/\d+\.htm’))
for link in links:
new_url = link[‘href’]
new_full_url = urljoin(page_url, new_url)
# print(new_full_url)
new_urls.add(new_full_url)
#print(new_urls)
return new_urls
def _get_new_data(self, page_url, soup):
res_data = {}
# url
res_data[‘url’] = page_url
# python
title_node = soup.find(‘dd’, class_=’lemmawgt-lemmatitle-title’).find(‘h1’)
res_data[‘title’] = title_node.get_text()
#
summary_node = soup.find(‘p’, class_=’lemma-summary’)
res_data[‘summary’] = summary_node.get_text()
# print(res_data)
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’)
# print(soup.prettify())
new_urls = self._get_new_urls(page_url, soup)
new_data = self._get_new_data(page_url, soup)
# print(‘mark’)
return new_urls, new_datahtml_outputer.py# coding:utf-8
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(”)
fout.write(”)
fout.write(”)
for data in self.datas:
fout.write(”)
fout.write(‘%s’ % data[‘url’])
fout.write(‘%s’ % data[‘title’])
fout.write(‘%s’ % data[‘summary’])
fout.write(”)
fout.write(”)
fout.write(”)
fout.write(”)
fout.close()运行
在命令行下,执行python spider_main.py。
编码问题
问题描述:unicodeencodeerror: ‘gbk’ codec can’t encode character ‘xa0’ in position …
使用python写文件的时候,或者将网络数据流写入到本地文件的时候,大部分情况下会遇到这个问题。网络上有很多类似的文章讲述如何解决这个问题,但是无非就是encode,decode相关的,这是导致该问题出现的真正原因吗?不是的。很多时候,我们使用了decode和encode,试遍了各种编码,utf8,utf-8,gbk,gb2312等等,该有的编码都试遍了,可是仍然出现该错误,令人崩溃。
在windows下面编写python脚本,编码问题很严重。将网络数据流写入文件时,我们会遇到几个编码:1、#encoding=’xxx’ 这里(也就是python文件第一行的内容)的编码是指该python脚本文件本身的编码,无关紧要。只要xxx和文件本身的编码相同就行了。 比如notepad++”格式”菜单里面里可以设置各种编码,这时需要保证该菜单里设置的编码和encoding xxx相同就行了,不同的话会报错。
2、网络数据流的编码比如获取网页,那么网络数据流的编码就是网页的编码。需要使用decode解码成unicode编码。
3、目标文件的编码 将网络数据流写入到新文件,写文件代码如下:
fout = open(‘output.html’,’w’)
fout.write(str)
在windows下面,新文件的默认编码是gbk,python解释器会用gbk编码去解析我们的网络数据流str,然而str是decode过的unicode编码,这样的话就会导致解析不了,出现上述问题。 解决的办法是改变目标文件的编码:
fout = open(‘output.html’,’w’, encoding=’utf-8′)运行结果
更多python抓取百度百科数据 相关文章请关注php中文网!