面向过程的方式

#!/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. 如何让socket编程非阻塞?

    import socket # 创建socket client = socket.socket() # 将原来阻塞的位置变成非阻塞(报错) client.setblocking(False) # 百度 ...

  2. Win7中的IIS配置asp时出现“出现403 文件夹禁止訪问错误”!

    Win7中的IIS配置asp时出现"出现403 文件夹禁止訪问错误"! 在[默认文档]中设一下启动文件即可了.

  3. Springboot入门-日志框架配置(转载)

    默认情况下,Spring Boot会用Logback来记录日志,并用INFO级别输出到控制台. Logback是log4j框架的作者开发的新一代日志框架,它效率更高.能够适应诸多的运行环境,同时天然支 ...

  4. mysql中变量的定义

    mysql中的变量定义 mysql的变量分为系统变量和用户变量,mysql系统定义的变量是系统变量,用户自己定义的变量为用户变量.对于系统变量,用户只能够改变它的值不能够创建新的系统变量.对于用户变量 ...

  5. HTML 块级元素与行内元素

    1.块元素一般都从新行开始,它可以容纳内联元素和其他块元素,常见块元素是段落标签'P".“form"这个块元素比较特殊,它只能用来容纳其他块元素. 2.如果没有css的作用,块元素 ...

  6. LeetCode:验证二叉搜索树【98】

    LeetCode:验证二叉搜索树[98] 题目描述 给定一个二叉树,判断其是否是一个有效的二叉搜索树. 假设一个二叉搜索树具有如下特征: 节点的左子树只包含小于当前节点的数. 节点的右子树只包含大于当 ...

  7. 杭电1025Constructing Roads In JGShining's Kingdom

    地址:http://acm.hdu.edu.cn/showproblem.php?pid=1025 题目: Problem Description JGShining's kingdom consis ...

  8. js小技巧(收集的)

    一.事件源对象 event.srcElement.tagName //IE浏览器 event.srcElement.type event.target.tagName //dom浏览器 event.t ...

  9. 【Java】Swing+IO流实现一个简单的文件加密程序(较完整版)

    留着参考 beans package com.my.bean; import java.io.Serializable; public class EncryptedFile implements S ...

  10. ASP.NET MVC 处理404与500错误页面的方法

    第一步创建ErrorPageController 第二步添加Oops页面 @{ ViewBag.Title = "Oops"; Layout = "~/Areas/Adm ...