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

yipeiwu_com4年前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'

相关文章

利用Python2下载单张图片与爬取网页图片实例代码

利用Python2下载单张图片与爬取网页图片实例代码

前言 一直想好好学习一下Python爬虫,之前断断续续的把Python基础学了一下,悲剧的是学的没有忘的快。只能再次拿出来滤了一遍,趁热打铁,通过实例来实践下,下面这篇文章主要介绍了关于...

python爬虫URL重试机制的实现方法(python2.7以及python3.5)

应用场景: 状态不是200的URL重试多次 代码比较简单还有部分注释 python2.7实现: # -*-coding:utf-8-*- """ ayou """ import...

python爬取网页内容转换为PDF文件

本文实例为大家分享了python爬取网页内容转换为PDF的具体代码,供大家参考,具体内容如下 将廖雪峰的学习教程转换成PDF文件,代码只适合该网站,如果需要其他网站的教程,可靠需要进行...

Python实现爬取百度贴吧帖子所有楼层图片的爬虫示例

Python实现爬取百度贴吧帖子所有楼层图片的爬虫示例

本文实例讲述了Python实现爬取百度贴吧帖子所有楼层图片的爬虫。分享给大家供大家参考,具体如下: 下载百度贴吧帖子图片,好好看 python2.7版本: #coding=utf-...

python爬取网易云音乐评论

本文实例为大家分享了python爬取网易云音乐评论的具体代码,供大家参考,具体内容如下 import requests import bs4 import json def g...