面向过程的方式

#!/usr/bin/env python
# -*- coding: utf-8 -*- import urllib2
import sys
import re
import os type = sys.getfilesystemencoding()
if __name__ == '__main__':
# 1.访问其中一个网页地址,获取网页源代码
url = 'http://www.qiushibaike.com/textnew/'
user_agent = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36'
headers = {'User-Agent': user_agent}
try:
req = urllib2.Request(url=url, headers=headers)
res = urllib2.urlopen(req)
html = res.read().decode("UTF-8").encode(type)
except urllib2.HTTPError as e:
print e
exit()
except urllib2.URLError as e:
print e
exit()
# 2.根据抓取到的网页源代码去提取想要的数据,帖子id,帖子内容
regex_content = re.compile(
'<div class="article block untagged mb15" id=(.*?)>(?:.*?)<div class="content">(.*?)</div>',
re.S)
items = re.findall(regex_content, html)
for item in items:
file_name = item[0].strip('\'')
content = item[1].strip().lstrip('<span>').rstrip('</span>').replace('\n', '').replace(
'<br/>', '\n')
# 3.保存抓取的数据到文件中
path = 'qiubai'
if not os.path.exists(path):
os.makedirs(path)
file_path = path + '/' + file_name + '.txt'
with open(file_path, 'w') as fp:
fp.write(content)
fp.close()

面向对象的方式

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import urllib2
import re
import os
import sys type = sys.getfilesystemencoding() class Spider:
def __init__(self):
self.url = 'http://www.qiushibaike.com/textnew/page/%s/?s=4979315'
self.user_agent = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36' # 获取网页源代码
def get_page(self, page_index):
headers = {'User-Agent': self.user_agent}
try:
req = urllib2.Request(url=self.url % str(page_index), headers=headers)
res = urllib2.urlopen(req)
html = res.read().decode("UTF-8").encode(type)
return html
except urllib2.HTTPError as e:
print e
exit()
except urllib2.URLError as e:
print e
exit() # 分析网页源代码
def analysis(self, html):
regex_content = re.compile(
'<div class="article block untagged mb15" id=(.*?)>(?:.*?)<div class="content">(.*?)</div>',
re.S)
items = re.findall(regex_content, html)
return items # 保存抓取的数据到文件中
def save(self, items, path):
if not os.path.exists(path):
os.makedirs(path)
for item in items:
file_name = item[0].strip('\'')
content = item[1].strip().lstrip('<span>').rstrip('</span>').replace('\n', '').replace(
'<br/>', '\n')
file_path = path + '/' + file_name + '.txt'
with open(file_path, 'w') as fp:
fp.write(content)
fp.close() # 运行的方法
def run(self):
print u'开始抓取内容...'
for i in range(1, 3):
content = self.get_page(i)
items = self.analysis(content)
self.save(items, 'qiubai')
print u'内容抓取完毕...' if __name__ == '__main__':
sp = Spider()
sp.run()

***微信扫一扫,关注“python测试开发圈”,了解更多测试教程!***

python 爬虫004-使用urllib2与正则表达式扒取糗事百科新鲜页首页帖子的更多相关文章

  1. 初识python 之 爬虫:使用正则表达式爬取“糗事百科 - 文字版”网页数据

    初识python 之 爬虫:使用正则表达式爬取"古诗文"网页数据 的兄弟篇. 详细代码如下: #!/user/bin env python # author:Simple-Sir ...

  2. python爬取糗事百科段子

    初步爬取糗事百科第一页段子(发布人,发布内容,好笑数和评论数) #-*-coding:utf--*- import urllib import urllib2 import re page = url ...

  3. Python爬虫实战一之爬取糗事百科段子

    大家好,前面入门已经说了那么多基础知识了,下面我们做几个实战项目来挑战一下吧.那么这次为大家带来,Python爬取糗事百科的小段子的例子. 首先,糗事百科大家都听说过吧?糗友们发的搞笑的段子一抓一大把 ...

  4. Python爬虫--抓取糗事百科段子

    今天使用python爬虫实现了自动抓取糗事百科的段子,因为糗事百科不需要登录,抓取比较简单.程序每按一次回车输出一条段子,代码参考了 http://cuiqingcai.com/990.html 但该 ...

  5. 转 Python爬虫实战一之爬取糗事百科段子

    静觅 » Python爬虫实战一之爬取糗事百科段子 首先,糗事百科大家都听说过吧?糗友们发的搞笑的段子一抓一大把,这次我们尝试一下用爬虫把他们抓取下来. 友情提示 糗事百科在前一段时间进行了改版,导致 ...

  6. Python爬虫爬取糗事百科段子内容

    参照网上的教程再做修改,抓取糗事百科段子(去除图片),详情见下面源码: #coding=utf-8#!/usr/bin/pythonimport urllibimport urllib2import ...

  7. 芝麻HTTP:Python爬虫实战之爬取糗事百科段子

    首先,糗事百科大家都听说过吧?糗友们发的搞笑的段子一抓一大把,这次我们尝试一下用爬虫把他们抓取下来. 友情提示 糗事百科在前一段时间进行了改版,导致之前的代码没法用了,会导致无法输出和CPU占用过高的 ...

  8. 8.Python爬虫实战一之爬取糗事百科段子

    大家好,前面入门已经说了那么多基础知识了,下面我们做几个实战项目来挑战一下吧.那么这次为大家带来,Python爬取糗事百科的小段子的例子. 首先,糗事百科大家都听说过吧?糗友们发的搞笑的段子一抓一大把 ...

  9. python网络爬虫--简单爬取糗事百科

    刚开始学习python爬虫,写了一个简单python程序爬取糗事百科. 具体步骤是这样的:首先查看糗事百科的url:http://www.qiushibaike.com/8hr/page/2/?s=4 ...

随机推荐

  1. CSRF Cross-site request forgery

    w 跨站请求伪造目标站---无知用户---恶意站 http://fallensnow-jack.blogspot.com/2011/08/webgoat-csrf.html https://wiki. ...

  2. Web 编程中编码问题

    1. 常见字符编码 iso-8859-1(不支持中文) gbk(国标码) utf-8 (万国码, 支持全世界的编码) 2. 响应编码 当使用 response.getWriter() 来向客户端发送字 ...

  3. Docker Libnetwork driver API

    以下内容均在libnetwork/driverapi目录下 Driver接口如下所示: // Driver is an interface that every plugin driver needs ...

  4. 我的Android进阶之旅------>Android自定义View实现带数字的进度条(NumberProgressBar)

    今天在Github上面看到一个来自于 daimajia所写的关于Android自定义View实现带数字的进度条(NumberProgressBar)的精彩案例,在这里分享给大家一起来学习学习!同时感谢 ...

  5. Linux(4)- centos7安装python3、Linux下安装、配置virtualenv、确保开发环境的一致性、虚拟环境之virtualenvwrapper、vim

    一.centos7安装python3 1.下载python3的源码包 下载地址:https://www.python.org/ftp/python/3.6.2/Python-3.6.2.tgz cd ...

  6. Oracle11g的安装卸载及经常使用工具的使用

    Oracle11g的安装卸载及经常使用工具的使用 目的: (1) 掌握Oracle 11g数据库的安装与卸载过程. Oracle11g的安装卸载及经常使用工具的使用 目的: (1) 掌握Oracle  ...

  7. (4.7)sql server2008 中的merge

    简介 Merge关键字是一个神奇的DML关键字.它在SQL Server 2008被引入,它能将Insert,Update,Delete简单的并为一句.MSDN对于Merge的解释非常的短小精悍:”根 ...

  8. 海报工厂之(一)android 如何给图片添加水印和文字

    在Android中如何给图片添加水印,下面截取了部分核心代码,仅供参考: /**      * 获取图片缩小的图片      * @param src      * @return      */   ...

  9. android 布局属性详解

    Android功能强大,界面华丽,但是众多的布局属性就害苦了开发者,下面这篇文章结合了网上不少资料. 第一类:属性值为true或falseandroid:layout_centerHrizontal ...

  10. HDU1421:搬寝室(线性dp)

    题目:http://acm.hdu.edu.cn/showproblem.php?pid=1421 又是一道,没有思想的题,看了题解,我发现我的dp题几乎都看了题解,我总是想不好状态转移方程,汗颜,以 ...