[Python爬虫]爬取百度百科python相关的1000个页面
2016-10-30 20:48
387 查看
以下内容参考自:http://www.imooc.com/learn/563《Python开发简单爬虫》写在前面:花了两天的时间学习《Python开发简单爬虫》,将视频的主要内容保存成文字,供自己复习。版权归慕课网和讲视频的老师所有。一、爬虫简介爬虫:一段自动抓取互联网信息的程序爬虫可以从一个url出发,访问其所关联的所有的url。并从每个url指向的网页中,获取我们所需要的信息。二、简单爬虫架构 1.Python简单爬虫架构(1)爬虫调度端:启动爬虫、停止爬虫、监视爬虫的运行情况。(2)在爬虫程序中,有三个模块:
1)Url管理器:管理将要爬取的url和已经爬取的url。将待爬取的url传送给网页下载器。 2)网页下载器:将Url指定的网页下载下来,保存为一个字符串。将这个字符串传送给网页解析器进行解析。 3)网页解析器:一方面,会解释出有价值的数据;另一方面,解析出字符串中的url,将其补充到url管理器。 这三个模块,形成了一个循环。只有有未爬取的url,这个循环就会一直继续下去。
2.Python简单爬虫架构的动态运行流程
三、分别讲解各模块设计思路
1.URL管理器
作用:管理待抓取URL集合和已抓取URL集合
目的:防止重复抓取、防止循环抓取
实现方式:
在这里,我们选用Python的set()来实现小型的url管理器
2.网页下载器
作用:将互联网上URL对应的网页下载到本地的工具
工作流程:
实现方式:
在这里,我们选择urllib2这个简单的模块,来实现代码的下载。
使用urllib2下载网页的三种方法:
<span style="font-size:12px;">#coding:utf8 import urllib2 import cookielib url = "http://www.baidu.com" print "first method" response1 = urllib2.urlopen(url) #if 200,succeed print response1.getcode() print len(response1.read()) print "second method" request = urllib2.Request(url); request.add_header("user_agent","Mozilla/5.0") response2 = urllib2.urlopen(request) print response2.getcode() print len(response2.read()) print "three method" cj = cookielib.CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) urllib2.install_opener(opener) response3 = urllib2.urlopen(url) print response3.getcode() print cj print len(response3.read())</span>3.网页解析器
作用:从网页中提取有价值的数据
从下载好的html网页或者字符串中,可以提取出url、有价值的数据。
类型:正则表达式、html.parser、BeautifulSoup、lxml
其中,BeautifulSoup这个第三方插件可以使用html.parser和lxml作为它的解析器。
其中,正则表达式是模糊匹配,另外三种则是结构化的解析。
附,结构化解析:
四、实战:使用Python爬虫抓取百度百科的1000个页面
1.分析目标
目标:百度百科Python词条相关词条网页-标题和简介
入口页:http://baike.baidu.com/view/21087.htm
URL格式:
--词条页面URL:/view/21087.htm
数据格式:
--标题:<dd class="lemmaWgt-lemmaTitle-title"><h1>***</h1></dd>
--简介:<div class="lemma-summary" label-module="lemmaSummary">***</div>
页面编码:UTF-8
2.调度程序
程序目录:
spider_main.py:
<span style="font-size:12px;"># coding:utf8from baike_spider import url_manager, html_downloader, html_parser,\html_outputerclass 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 = 1self.urls.add_new_url(root_url)while self.urls.has_new_url():try:new_url = self.urls.get_new_url()print 'crow %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:breakcount = count + 1except: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)</span>3.URL管理器
url_manager.py:
<span style="font-size:12px;"># coding:utf8class UrlManager(object):def __init__(self):self.new_urls = set()self.old_urls = set()def add_new_url(self, url):if url is None:returnif 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:returnfor url in urls:self.add_new_url(url)def has_new_url(self):return len(self.new_urls) != 0def get_new_url(self):new_url = self.new_urls.pop()self.old_urls.add(new_url)return new_url</span>
4.HTML下载器
html_downloader.py:
<span style="font-size:12px;"># coding:utf8import urllib2class HtmlDownloader(object):def download(self,url):if url is None:return Noneresponse = urllib2.urlopen(url)if response.getcode() != 200:return Nonereturn response.read()</span>
5.HTML解析器:
html_parser.py:
<span style="font-size:12px;"># coding:utf8from bs4 import BeautifulSoupimport re;import urlparseclass HtmlParser(object):def _get_new_urls(self, page_url, soup):new_urls = set()# /view/123.htmlinks = soup.find_all('a',href=re.compile(r"/view/\d+\.htm") )for link in links:new_url = link['href']new_full_url = urlparse.urljoin(page_url, new_url)new_urls.add(new_full_url)return new_urlsdef _get_new_data(self, page_url, soup):res_data = {}#url,current urlres_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_datadef parse(self, page_url, html_cont):if page_url is None or html_cont is None:returnsoup = 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</span>
6.HTML输出器:
html_outputer.py:
<span style="font-size:12px;"># coding:utf8class HtmlOutputer(object):def __init__(self):self.datas = []def collect_data(self, data):if data is None:returnself.datas.append(data)#print datadef output_html(self):fout = open('output.html', 'w')fout.write('<html>')fout.write("<head><meta charset='utf-8'></head>")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'].encode('utf-8'))fout.write('<td>%s</td>' % data['summary'].encode('utf-8'))fout.write('</tr>')fout.write('</table>')fout.write('</body>')fout.write('</html>')fout.close()</span>以上就是完整的实现代码啦。
五、运行结果
首先,在console中会打印出相应信息。
同时,还会输出一个html。
至此,结束。整个工程代码如下:
python爬虫-抓取百度百科页面
相关文章推荐
- Python爬虫----实例: 抓取百度百科Python词条相关1000个页面数据
- 慕课爬虫实战 爬取百度百科Python词条相关1000个页面数据
- 实践项目十:爬取百度百科Python词条相关1000个页面数据(慕课简单爬虫实战)
- Python基础爬虫实战实例----爬取1000个Python百度百科词条及相关词条的标题和简介
- Java爬虫爬取python百度百科词条及相关词条页面
- 第一个python爬虫(python3爬取百度百科1000个页面)
- 编写Python代码——爬取百度百科Python词条相关1000个页面数据【未完慕课】
- Python爬取百度百科1000个页面
- python爬虫主要就是五个模块:爬虫启动入口模块,URL管理器存放已经爬虫的URL和待爬虫URL列表,html下载器,html解析器,html输出器 同时可以掌握到urllib2的使用、bs4(BeautifulSoup)页面解析器、re正则表达式、urlparse、python基础知识回顾(set集合操作)等相关内容。
- python 爬虫——针对query爬取百度百科页面
- Python开发简单爬虫(二)---爬取百度百科页面数据
- 简单爬虫-爬取百度百科1000个页面
- Python3_第一个简单爬虫开发_爬取百度百科1000个词条_参照慕课网教程实现
- 一个简单的爬虫程序(爬取百度百科关于python的一千个页面)
- 使用python爬取百度百科python词条相关的1000个网页的标题和简介
- Python 简易网络爬虫的编写——抓取任意页面数目百度百科内容
- Python静态网页爬虫相关知识
- Python3.5爬虫入门示例-获取百度首页及相关的html页面
- 使用python实现简单的百度百科词条爬虫
- Python简易百度百科爬虫