面向过程的方式

#!/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. 2015-03-12——简析DOM2级事件

    DOM2级事件 事件的几种类型:对象事件,鼠标事件,键盘事件,表单事件,W3CDOM事件,以及针对浏览器的事件. 对象事件:window对象,也是javascript对象.load  适用于windo ...

  2. make Makefile 与 cmake CMakeLists.txt

    make Makefile 与 cmake CMakeLists.txt 大家都知道,写程序大体步骤为: 1.用编辑器编写源代码,如.c文件. 2.用编译器编译代码生成目标文件,如.o. 3.用链接器 ...

  3. (数据库之pymysql)

    权限管理http://www.cnblogs.com/linhaifeng/articles/7267587.html#_label6一.pymysql模块(安装与查询) 1.安装pymysql(py ...

  4. &lt;context-param&gt;与&lt;init-param&gt;的差别与作用

    <context-param>的作用: web.xml的配置中<context-param>配置作用 1. 启动一个WEB项目的时候,容器(如:Tomcat)会去读它的配置文件 ...

  5. C#设置当前程序通过IE代理服务器上网

    注意:以下设置只在当前程序中有效,对IE浏览器无效,且关闭程序后,自动释放代码. using System; using System.Collections.Generic; using Syste ...

  6. 《深度学习》Textbook第十章学习笔记

    深度学习 第10章 序列建模:循环和递归网络 1.循环神经网络介绍 相比卷积神经网络:专门用于处理网格化的数据(如图像),可以很容易扩展到更具有很大宽度和高度的图像,以及处理大小可变的图像: 循环神经 ...

  7. go——标准命令

    Go本身包含大量用户处理Go程序的命令和工具. 1.子命令 go命令的子命令:build:用于编译指定的代码包或Go语言源码文件. 命令源码文件会被编译成可执行文件,并存放到命令执行的目录或指定目录下 ...

  8. 按钮js跳转到非表单提交页

    <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...

  9. java HttpURLConnection 请求实例

    package app.works; import org.json.JSONObject; import java.io.BufferedReader; import java.io.InputSt ...

  10. SqlHelper简单实现(通过Expression和反射)7.MySql数据处理类

    MySql的数据处理类和Sql Server没有太大差别,从思路上来说没有区别,所以此处只是给出代码,不再多加解释了. using System; using System.Configuration ...