用python编写简单爬虫
需求:抓取百度百科python词条相关词条网页的标题和简介,并将数据输出在一个html表格中
入口页:python的百度词条页 https://baike.baidu.com/item/Python/407313
词条页面URL:'/item/%E8%AE%A1%E7%AE%97%E6%9C%BA%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1%E8%AF%AD%E8%A8%80' 注意:这不是一个完整的url,需要对之进行拼接
数据格式:
-标题:<dd class="lemmaWgt-lemmaTitle-title"><h1>***</h1></dd>
-简介:<div class='lemma-summary'>***</div>
页面编码:UTF-8 实例代码:
文件目录结构如图

入口文件(spider_main.py):
# coding:utf-8
import url_manager
import html_parser
import html_downloader
import 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(): # 如果有待爬取的url
try:
new_url = self.urls.get_new_url() # 取一个待爬取的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) # 解析页面得到新的url和一些数据
self.urls.add_new_urls(new_urls) # 将新得到的url添加到url管理器
self.outputer.collect_data(new_data) # 将获取到的数据添加到output文件中
if count == 10:
break
count += 1
except Exception as e:
print e
self.outputer.output_html() if __name__ == '__main__':
obj_spider = SpiderMain()
obj_spider.craw('https://baike.baidu.com/item/Python/407313')
url管理文件(url_manager.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_url
页面源码下载(html_downloader.py):
# coding:utf-8
import urllib2 class HtmlDownloader(object):
def download(self, url):
if url is None:
return None
response = urllib2.urlopen(url)
if response.getcode() != 200:
return None
return response.read()
源码解析(html_parser.py):
# coding:utf-8
from bs4 import BeautifulSoup
import urlparse
import re class HtmlParser(object):
def _get_new_urls(self, page_url, soup):
new_urls = set()
# 页面中的链接格式:/item/xxx
links = soup.find_all('a', href=re.compile(r"/item/(.*)")) # 得到所有的url的标签
for link in links:
new_url = link['href'] # 获取所有的链接
new_full_url = urlparse.urljoin(page_url, new_url) # 让new_url按照page_url的格式拼接成一个完整的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
# <dd class="lemmaWgt-lemmaTitle-title"><h1>Python</h1></dd>
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"> 简介的html
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_output.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): # 将数据输出为html
fout = open('output.html', 'w')
fout.write('<html>')
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>')
用python编写简单爬虫的更多相关文章
- Python 利用Python编写简单网络爬虫实例3
利用Python编写简单网络爬虫实例3 by:授客 QQ:1033553122 实验环境 python版本:3.3.5(2.7下报错 实验目的 获取目标网站“http://bbs.51testing. ...
- Python 利用Python编写简单网络爬虫实例2
利用Python编写简单网络爬虫实例2 by:授客 QQ:1033553122 实验环境 python版本:3.3.5(2.7下报错 实验目的 获取目标网站“http://www.51testing. ...
- Python开发简单爬虫 - 慕课网
课程链接:Python开发简单爬虫 环境搭建: Eclipse+PyDev配置搭建Python开发环境 Python入门基础教程 用Eclipse编写Python程序 课程目录 第1章 课程介绍 ...
- 使用Python编写简单的端口扫描器的实例分享【转】
转自 使用Python编写简单的端口扫描器的实例分享_python_脚本之家 http://www.jb51.net/article/76630.htm -*- coding:utf8 -*- #!/ ...
- python编写简单的html登陆页面(4)
python编写简单的html登陆页面(4) 1 在python编写简单的html登陆页面(2)的基础上在延伸一下: 可以将动态态分配数据,建立表格,存放学生信息 2 实现的效果如下: 3 动 ...
- python编写简单的html登陆页面(3)
1 在python编写简单的html登陆页面(2)的基础上在延伸一下: 可以将静态分配数据,建立表格,存放学生信息 2 加载到静态数据 3 html的编写直接在表格里添加一组数据就行了 4 V ...
- python编写简单的html登陆页面(2)
1 在python编写简单的html登陆页面(1)的基础上在延伸一下: 可以将动态分配数据,实现页面跳转功能: 2 跳转到新的页面:return render_template('home1.ht ...
- 用Python编写简单的发红包程序和计算器原理
用Python编写简单的发红包程序: 第一种解法:数轴方法解决 import random def red_packet(money,num): money = money * 100 #将钱数转换成 ...
- 使用Python编写简单网络爬虫抓取视频下载资源
我第一次接触爬虫这东西是在今年的5月份,当时写了一个博客搜索引擎.所用到的爬虫也挺智能的,起码比电影来了这个站用到的爬虫水平高多了! 回到用Python写爬虫的话题. Python一直是我主要使用的脚 ...
随机推荐
- Three.js基础:导入STL模型文件
stlloadertest.html: <!DOCTYPE html> <html lang="en"> <head> <title> ...
- powmock
Verify 方法是否调用 Ve ri fy 核实 万花筒 瑞雪 发大财 Local Variable 局部变量@RunWith 运行器@PrepareForTest 提前准备 有返回值测试 void ...
- Maven的生命周期阶段
一.Maven的生命周期 Maven的生命周期就是对所有的构建过程进行抽象和统一.包含了项目的清理.初始化.编译.测试.打包.集成测试.验证.部署和站点生成等几乎所有的构建步骤. Maven的生命周期 ...
- yii2: oracle汉字占用字节长度
OCIStmtExecute: ORA-12899: value too large for column "WSG"."WX_ENTER_TASTE".&qu ...
- serialVersionUID 作用
一个类在序列化时,用来记录当前类的版本号.在反序列化时,首先获取当前类的版本号,不一致则报异常. 若版本号一致,但两个类不一致.写肯定全部写进去.但提取时 类若没有这个字段,则不提取.若提取类多个字段 ...
- 018对象——对象 get_class get_declared_classes get_declared_interfaces
<?php /** * 对象 get_class get_declared_classes get_declared_interfaces */ //get_class() 获得对象的类名,区分 ...
- 基于Python实现的四则运算生成程序
Github项目地址:传送门 小组成员:黄晓彬(代码实现) 黄钰城(代码审查) 需求: 1. 使用 -n 参数控制生成题目的个数. 2. 使用 -r 参数控制题目中数值(自然数.真分数和真分数分母)的 ...
- SpringCloud教程 | 第十篇: 高可用的服务注册中心
版权声明:本文为博主原创文章,欢迎转载,转载请注明作者.原文超链接 ,博主地址:http://blog.csdn.net/forezp. http://blog.csdn.net/forezp/art ...
- 【dlbook】数学基础
[代数] Moore-Penrose 伪逆 [概率信息论] 自信息,香农熵,衡量两个分布的差异:kl散度 \ 交叉熵 [数值] 溢出: softmax计算的时候要关注上溢和下溢,如果所有X都相等且为很 ...
- Cisco DHCP 配置要点
实验拓扑图:IOU5/6/7模拟主机 IOU1为DHCP服务器 IOU2为DHCP中继器 IOU3/4为局域网内的交换机 在IOU1中配置DHCP配置 IOU2作为DHCP中继,在E0/0.10和E0 ...