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'

相关文章

pycharm下打开、执行并调试scrapy爬虫程序的方法

pycharm下打开、执行并调试scrapy爬虫程序的方法

首先得有一个Scrapy项目,我在Desktop上新建一个Scrapy的项目叫test,在Desktop目录打开命令行,键入命令:scrapy startproject test1...

Python中urllib+urllib2+cookielib模块编写爬虫实战

Python中urllib+urllib2+cookielib模块编写爬虫实战

超文本传输协议http构成了万维网的基础,它利用URI(统一资源标识符)来识别Internet上的数据,而指定文档地址的URI被称为URL(既统一资源定位符),常见的URL指向文件、目录...

python 3利用BeautifulSoup抓取div标签的方法示例

前言 本文主要介绍的是关于python 3用BeautifulSoup抓取div标签的方法示例,分享出来供大家参考学习,下面来看看详细的介绍: 示例代码: # -*- coding:...

PHP网页抓取之抓取百度贴吧邮箱数据代码分享

PHP网页抓取之抓取百度贴吧邮箱数据代码分享

百度贴吧大家都经常逛,去逛百度贴吧的时候,经常会看到楼主分享一些资源,要求留下邮箱,楼主才给发。 对于一个热门的帖子,留下的邮箱数量是非常多的,楼主需要一个一个的去复制那些回复的邮箱,...

Python中Scrapy爬虫图片处理详解

下载图片 下载图片有两种方式,一种是通过 Requests 模块发送 get 请求下载,另一种是使用 Scrapy 的 ImagesPipeline 图片管道类,这里主要讲后者。 安装...