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

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

相关文章

玩转python爬虫之URLError异常处理

本节在这里主要说的是URLError还有HTTPError,以及对它们的一些处理。 1.URLError 首先解释下URLError可能产生的原因: 网络无连接,即本机无法上网...

详解Python3网络爬虫(二):利用urllib.urlopen向有道翻译发送数据获得翻译结果

详解Python3网络爬虫(二):利用urllib.urlopen向有道翻译发送数据获得翻译结果

上一篇内容,已经学会了使用简单的语句对网页进行抓取。接下来,详细看下urlopen的两个重要参数url和data,学习如何发送数据data 一、urlopen的url参数 Agent...

Python实现爬虫爬取NBA数据功能示例

本文实例讲述了Python实现爬虫爬取NBA数据功能。分享给大家供大家参考,具体如下: 爬取的网站为:stat-nba.com,这里爬取的是NBA2016-2017赛季常规赛至2017年...

python3实现网络爬虫之BeautifulSoup使用详解

python3实现网络爬虫之BeautifulSoup使用详解

这一次我们来了解一下美味的汤--BeautifulSoup,这将是我们以后经常使用的一个库,并且非常的好用。 BeautifuleSoup库的名字取自刘易斯·卡罗尔在《爱丽丝梦游仙境》里...

Python 爬虫之超链接 url中含有中文出错及解决办法

Python 爬虫之超链接 url中含有中文出错及解决办法 python3.5 爬虫错误: UnicodeEncodeError: 'ascii' codec can't encod...