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使用Beautiful Soup包编写爬虫时的一些关键点

1.善于利用soup节点的parent属性 比如对于已经得到了如下html代码: <td style="padding-left:0" width="60%"><l...

python网络爬虫 CrawlSpider使用详解

CrawlSpider 作用:用于进行全站数据爬取 CrawlSpider就是Spider的一个子类 如何新建一个基于CrawlSpider的爬虫文件 sc...

Docker部署Python爬虫项目的方法步骤

1) 首先安装docker: # 用 yum 安装并启动 yum install docker -y && systemctl start docker 2) 下载自定义镜像需要...

Python多线程爬取豆瓣影评API接口

爬虫库 使用简单的requests库,这是一个阻塞的库,速度比较慢。 解析使用XPATH表达式 总体采用类的形式 多线程 使用concurrent.future并发模块,建立线程...