您的位置:首页 > 编程语言 > Python开发

[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 爬虫
相关文章推荐