面向过程的方式

#!/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. Linux network 资料链接

    1.iptables 基础 https://wiki.centos.org/HowTos/Network/IPTables 2.HOWTOs on netfilter site http://www. ...

  2. python列表套字典数据类型转换

    1.题目 list3 = [ {'name':'Alex','hobby':'抽烟'}, {'name':'Alex', 'hobby':'喝酒'}, {'name':'Alex', 'hobby': ...

  3. Vue(2)- v-model、局部组件和全局组件、父子组件传值、平行组件传值

    一.表单输入绑定(v-model 指令) 可以用 v-model 指令在表单 <input>.<textarea> 及 <select> 元素上创建双向数据绑定. ...

  4. 快速入门Python中文件读写IO是如何来操作外部数据的?

    读写文件是最常见的IO操作.Python内置了读写文件的函数,用法和C是兼容的. 读写文件前,我们先必须了解一下,在磁盘上读写文件的功能都是由操作系统提供的,现代操作系统不允许普通的程序直接操作磁盘, ...

  5. STL sort “invalid operator <”

    跟踪了下,是比较函数(下面的_Pred)的问题: template<class _Pr, class _Ty1, class _Ty2> inline bool _Debug_lt_pre ...

  6. ThinkPHP框架基础3

    连接数据库 把convertion.php数据库相关的设置复制到config.php 在config.php做数据库连接配置,设置好数据 制作model模型 a)        model本身就是一个 ...

  7. sublime Text emmet插件使用手册

    转自:http://www.w3cplus.com/tools/emmet-cheat-sheet.html 介绍 Emmet (前身为 Zen Coding) 是一个能大幅度提高前端开发效率的一个工 ...

  8. Spark机器学习1·编程入门(scala/java/python)

    Spark安装目录 /Users/erichan/Garden/spark-1.4.0-bin-hadoop2.6 基本测试 ./bin/run-example org.apache.spark.ex ...

  9. What is CRC and how does it works?

    What is CRC and how does it works? CRC errors refer to Layer 1 or 2 issues. Two things you should ch ...

  10. UEFI引导修复

    一.用bcbboot自动修复 我们建议大家启动64位8PE,用它带的bcdboot来修复. (一)指定esp分区修复 环境为64位8PE,bios/uefi启动进入下都可以 1.启动64位8PE,并用 ...