Python使用urllib2模块抓取HTML页面资源的实例分享

yipeiwu_com5年前Python爬虫

先把要抓取的网络地址列在单独的list文件中

//www.jb51.net/article/83440.html
//www.jb51.net/article/83437.html
//www.jb51.net/article/83430.html
//www.jb51.net/article/83449.html

然后我们来看程序操作,代码如下:

#!/usr/bin/python

import os
import sys
import urllib2
import re

def Cdown_data(fileurl, fpath, dpath):
 if not os.path.exists(dpath):
  os.makedirs(dpath)
 try:
  getfile = urllib2.urlopen(fileurl) 
  data = getfile.read()
  f = open(fpath, 'w')
  f.write(data)
  f.close()
 except:
 print 

with open('u1.list') as lines:
 for line in lines:
  URI = line.strip()
  if '?' and '%' in URI:
   continue
 elif URI.count('/') == 2:
   continue
  elif URI.count('/') > 2:
   #print URI,URI.count('/')
  try:
    dirpath = URI.rpartition('/')[0].split('//')[1]
    #filepath = URI.split('//')[1].split('/')[1]
    filepath = URI.split('//')[1]
   if filepath:
     print URI,filepath,dirpath
     Cdown_data(URI, filepath, dirpath)
   except:
    print URI,'error'

相关文章

scrapy spider的几种爬取方式实例代码

本节课介绍了scrapy的爬虫框架,重点说了scrapy组件spider。 spider的几种爬取方式: 爬取1页内容 按照给定列表拼出链接爬取多页 找到‘下一页'标签进行...

Python爬虫使用浏览器cookies:browsercookie过程解析

很多用Python的人可能都写过网络爬虫,自动化获取网络数据确实是一件令人愉悦的事情,而Python很好的帮助我们达到这种愉悦。然而,爬虫经常要碰到各种登录、验证的阻挠,让人灰心丧气(网...

python使用beautifulsoup4爬取酷狗音乐代码实例

这篇文章主要介绍了python使用beautifulsoup4爬取酷狗音乐代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 小编...

Python 爬虫学习笔记之单线程爬虫

Python 爬虫学习笔记之单线程爬虫

介绍 本篇文章主要介绍如何爬取麦子学院的课程信息(本爬虫仍是单线程爬虫),在开始介绍之前,先来看看结果示意图 怎么样,是不是已经跃跃欲试了?首先让我们打开麦子学院的网址,然后找到麦子学...

python妹子图简单爬虫实例

本文实例讲述了python妹子图简单爬虫实现方法。分享给大家供大家参考。具体如下: #!/usr/bin/env python #coding: utf-8 import urlli...