脚本专栏 
首页 > 脚本专栏 > 浏览文章

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

(编辑:jimmy 日期: 2024/5/9 浏览:3 次 )

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

https://www.jb51.net/article/83440.html
https://www.jb51.net/article/83437.html
https://www.jb51.net/article/83430.html
https://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二叉搜索树与双向链表转换实现方法
下一篇:Python实现简单字典树的方法
一句话新闻
高通与谷歌联手!首款骁龙PC优化Chrome浏览器发布
高通和谷歌日前宣布,推出首次面向搭载骁龙的Windows PC的优化版Chrome浏览器。
在对骁龙X Elite参考设计的初步测试中,全新的Chrome浏览器在Speedometer 2.1基准测试中实现了显著的性能提升。
预计在2024年年中之前,搭载骁龙X Elite计算平台的PC将面世。该浏览器的提前问世,有助于骁龙PC问世就获得满血表现。
谷歌高级副总裁Hiroshi Lockheimer表示,此次与高通的合作将有助于确保Chrome用户在当前ARM兼容的PC上获得最佳的浏览体验。
友情链接:杰晶网络 DDR爱好者之家 南强小屋 黑松山资源网 白云城资源网