python爬虫—爬取百度百科数据
爬虫框架:开发平台 centos6.7 根据慕课网爬虫教程编写代码 片区百度百科url,标题,内容
#!/usr/bin/python
#-*- coding: utf8 -*- import html_downloader
import html_outputer
import html_parser
import url_manager class SpiderMain(object):
def __init__(self):
#初始化url管理器
self.urls = url_manager.UrlManager()
#初始化url下载器
self.downloader = html_downloader.HtmlDownloader()
#初始化url解析器
self.parser = html_parser.HtmlParser()
#初始化url输出
self.outputer = html_outputer.HtmlOutputer() def craw(self, root_url):
count = 1
#url管理器中添加一个new url
self.urls.add_new_url(root_url)
#判断是否有新的URL 开始爬取
while self.urls.has_new_url():
try:
#得到新的url
new_url = self.urls.get_new_url()
print 'craw %d : %s' % (count, new_url)
#下载新的url的数据
html_cont = self.downloader.download(new_url)
#解析出来url的内容和地址
new_urls, new_data = self.parser.parse(new_url, html_cont)
#新的url补充进url管理器
self.urls.add_new_urls(new_urls)
#输出数据
self.outputer.collect_data(new_data) if count == 1001:
break
count = count + 1
print count
except:
html_parser.py
#!/bin/usr/python
#-*- coding:utf8 -*- from bs4 import BeautifulSoup
import re
import urlparse class HtmlParser(object):
'''
解析器
''' def _get_new_urls(self, page_url, soup):
new_urls = set()
links = 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_urls def _get_new_data(self, page_url, soup):
res_data = {} res_data['url'] = page_url title_node = soup.find('dd', class_="lemmaWgt-lemmaTitle-title").find('h1')
res_data['title'] = title_node.get_text() summary_node = soup.find('div', class_="lemma-summary")
res_data['summary'] = summary_node.get_text()
print res_data['summary'] 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)
print new_data
return new_urls, new_data
html_outputer.py
#!/usr/bin/python
#-*- coding:utf8 -*- 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') fout.write("<html>")
fout.write("<body>")
fout.write("<head>")
fout.write('<meta charset="utf-8">')
fout.write("</head>")
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()
html_downloader.py
#!/usr/bin/python
#-*- coding:utf8 -*- import urllib2 class HtmlDownloader(object):
'''
下载器
''' def download(self, url):
if url is None:
return None response = urllib2.urlopen(url) if response.getcode() != 200:
print '请求失败'
return None return response.read()
url_manager.py
#!/usr/bin/python
#-*- coding:utf8 -*- class UrlManager(object):
'''
url管理器
'''
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):
if len(self.new_urls) != 0:
return len(self.new_urls)
else:
print '没有新的url' def get_new_url(self):
new_url = self.new_urls.pop()
self.old_urls.add(new_url)
return new_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)
python爬虫—爬取百度百科数据的更多相关文章
- python爬虫-爬取百度图片
python爬虫-爬取百度图片(转) #!/usr/bin/python# coding=utf-8# 作者 :Y0010026# 创建时间 :2018/12/16 16:16# 文件 :spider ...
- Python爬虫 - 爬取百度html代码前200行
Python爬虫 - 爬取百度html代码前200行 - 改进版, 增加了对字符串的.strip()处理 源代码如下: # 改进版, 增加了 .strip()方法的使用 # coding=utf-8 ...
- 写一个python 爬虫爬取百度电影并存入mysql中
目标是利用python爬取百度搜索的电影 在类型 地区 年代各个标签下 电影的名字 评分 和图片连接 以及 电影连接 首先我们先在mysql中建表 create table liubo4( id in ...
- python爬虫-爬取豆瓣电影数据
#!/usr/bin/python# coding=utf-8# 作者 :Y0010026# 创建时间 :2018/12/16 16:27# 文件 :spider_05.py# IDE :PyChar ...
- python简单爬虫爬取百度百科python词条网页
目标分析:目标:百度百科python词条相关词条网页 - 标题和简介 入口页:https://baike.baidu.com/item/Python/407313 URL格式: - 词条页面URL:/ ...
- Python爬虫爬取百度翻译之数据提取方法json
工具:Python 3.6.5.PyCharm开发工具.Windows 10 操作系统 说明:本例为实现输入中文翻译为英文的小程序,适合Python爬虫的初学者一起学习,感兴趣的可以做英文翻译为中文的 ...
- Python爬虫爬取百度贴吧的帖子
同样是参考网上教程,编写爬取贴吧帖子的内容,同时把爬取的帖子保存到本地文档: #!/usr/bin/python#_*_coding:utf-8_*_import urllibimport urlli ...
- Python爬虫爬取百度贴吧的图片
根据输入的贴吧地址,爬取想要该贴吧的图片,保存到本地文件夹,仅供参考: #!/usr/bin/python#_*_coding:utf-8_*_import urllibimport urllib2i ...
- python爬虫爬取赶集网数据
一.创建项目 scrapy startproject putu 二.创建spider文件 scrapy genspider patubole patubole.com 三.利用chrome浏览器 ...
随机推荐
- [备忘] Automatically reset Windows Update components
这两天遇到Windows 10的更新问题,官方有一个小工具,可以用来修复Windows Update的问题,备忘如下 https://support.microsoft.com/en-us/kb/97 ...
- 关于Simple_html_dom的小应用
今天一同学给我推荐了本书,说是刚出不久,内容还不错,是心灵鸡汤类的书,于是按捺不住就像在网上下一本,可是木有资源肿么办.只有在线看的,作为一个准码农,所以甭废话了,咱得用代码解决问题对吧…… 1.工欲 ...
- php使用js对表格进行排序
<!DOCTYPE> <html> <head> <meta http-equiv="Content-type" content=&quo ...
- hibernate笔记--使用注解(annotation)方式配置单(双)向多对一的映射关系
前面几篇都是介绍的用配置文件来实现实体类到数据库表的映射,这种方式是比较麻烦的,每一个pojo类都需要写一个相应的*.hbm.xml,无疑增加了很多代码量,不过也有优点就是利于维护,为了方便开发,Hi ...
- 7.2 数据注解属性--TimeStamp特性【Code-First 系列】
TimeStamp特性可以应用到领域类中,只有一个字节数组的属性上面,这个特性,给列设定的是tiemStamp类型.在并发的检查中,Code-First会自动使用这个TimeStamp类型的字段. 下 ...
- WCF入门教程(一)简介
WCF入门教程(一)简介 1.WCF是什么? WCF( Windows Communication Foundation), 是Microsoft为构建面向服务的应用提供的分布式通信编程框架,是.NE ...
- ASP.NET MVC4实现TinyMCE 4.0.20自定义上传功能
tinymce 插件不提供免费的本地图片上传功能,所以自己将uploadify这个上传插件整合到tinymce,实现本地上传,还用到了jquery.ui插件,先展示全部的代码 @model TinyM ...
- 背水一战 Windows 10 (24) - MVVM: 通过 Binding 或 x:Bind 结合 Command 实现,通过非 ButtonBase 触发命令
[源码下载] 背水一战 Windows 10 (24) - MVVM: 通过 Binding 或 x:Bind 结合 Command 实现,通过非 ButtonBase 触发命令 作者:webabcd ...
- C++_系列自学课程_第_6_课_bitset集_《C++ Primer 第四版》
在C语言中要对一个整数的某一个位进行操作需要用到很多的技巧.这种情况在C++里面通过标准库提供的一个抽象数据类型 bitset得到了改善. 一.标准库bitset类型 1.bitset的作用 bits ...
- 转载:《TypeScript 中文入门教程》 16、Symbols
版权 文章转载自:https://github.com/zhongsp 建议您直接跳转到上面的网址查看最新版本. 介绍 至ECMAScript 2015开始,symbol成为了一种新的原始类型,就像n ...