Python下载懒人图库JavaScript特效

yipeiwu_com6年前Python基础

这是一个简单的Python脚本,主要从懒人图库下载JavaScript特效模板,在脚本中使用了gevent这个第三方库,使用的时候需要先安装。

#!/usr/bin/python
# -*- coding: utf-8 -*-
 
import urllib,os,sys
import gevent,re
from gevent import monkey
from bs4 import BeautifulSoup
gevent.monkey.patch_socket()
 
'''
Description:Python 爬虫抓取懒人图库的JS脚本模板
Author:admin
Create-Date:2015-05-25
Version:1.0
'''
 
HTTP_URL = 'http://www.lanrentuku.com%s'
DOWNLOAD_URL = HTTP_URL[:-2] + '/js/d%szip'
reg=r'\d{1,}\.+'
 
def encode(text):
  return text.encode("utf8")
 
def createDirectory(curPath):
  myPath = os.path.join(getSubDirectory(), u'JS代码模板')
  if not os.path.exists(myPath):
    os.mkdir(myPath)
  return os.path.join(myPath, curPath)
 
def getSubDirectory():
  return os.getcwd()
 
def schedule(a, b, c): 
  per = 100.0 * a * b / c
  if per > 100 :
    per = 100
  sys.stdout.write('%.1f%%\r' % per)
  sys.stdout.flush()
 
def geturllist(url):
  url_list = {}
  html = urllib.urlopen(url)
  content = html.read()
  html.close()
  # 用BeautifulSoup解析
  decodeHtml = BeautifulSoup(content)
  try:
    aTags = decodeHtml.find_all('div', {'class':'list-pngjs'})[0].find_all('a')
  except IndexError, e:
    print e
    aTags = None
  # 获取链接地址和标题
  if aTags is not None:
    for a_tag in aTags:
      url_list[HTTP_URL % a_tag.get('href')] = a_tag.get_text()
  return url_list
  
def download(down_url):
  try:
    m=re.search(reg,down_url[0])
    name = DOWNLOAD_URL % m.group(0)
    urllib.urlretrieve(name,createDirectory(down_url[1] + name[-4:]),schedule)
  except Exception, e:
    print e.message
  
def getpageurl(xUrl):
  # 进行列表页循环
  return [xUrl % page for page in xrange(1,49)]
 
if __name__ == '__main__':
  jobs = []
  pageurl = getpageurl('http://www.lanrentuku.com/js/p%s.html')
  # 爬取所有链接
  for i in pageurl:
    for k in geturllist(i).items():
      jobs.append(gevent.spawn(download, k))
  gevent.joinall(jobs)

以上所述就是本文的全部内容了,希望大家能够喜欢。

相关文章

python字符串与url编码的转换实例

主要应用的场景 爬虫生成带搜索词语的网址 1.字符串转为url编码 import urllib poet_name = "李白" url_code_name = urllib.quo...

python清除字符串里非字母字符的方法

本文实例讲述了python清除字符串里非字母字符的方法。分享给大家供大家参考。具体如下: s = "hello world! how are you? 0" # Short...

详解使用 pyenv 管理多个版本 python 环境

 随着同时开发的项目越来越多,需要不停的在各个不同版本的 python 环境之间切换,所以想到了pyenv。以前一直使用的 virtualenv只能管理同一个 python 版...

利用Pandas读取文件路径或文件名称包含中文的csv文件方法

利用Pandas读取文件路径或文件名称包含中文的csv文件方法

利用Pandas的read_csv函数导入数据文件时,若文件路径或文件名包含中文,会报错,无法导入: import pandas as pd df=pd.read_csv('E:/学...

python 统计一个列表当中的每一个元素出现了多少次的方法

如下所示: #coding=utf-8 #方式一 print('*'*20 + '方式一' + '*'*20) li1 = [1,2,2,3,3,3,4,4,4,4,5,5,5,5,...