zoukankan      html  css  js  c++  java
  • 【转载】Python2爬虫之爬取某一路径的所有html文件

     1 # -*- coding: UTF-8 -*- 
     2 import re
     3 import urllib2
     4 
     5 from collections import deque
     6 
     7 # 保存文件的后缀
     8 SUFFIX='.html'
     9 # 提取文章标题的正则表达式
    10 REX_TITLE=r'<title>(.*?)</title>'
    11 # 提取所需链接的正则表达式
    12 REX_URL=r'/jdbc/(.+?).html'
    13 # 种子url,从这个url开始爬取
    14 BASE_URL='http://www.yiibai.com/jdbc/'
    15 
    16 
    17 # 将获取到的文本保存为html文件
    18 def saveHtml(file_name,file_content):
    19 #    注意windows文件命名的禁用符,比如 /
    20     with open(file_name.replace('/', '_')+SUFFIX,"wb") as f:
    21 #   写文件用bytes而不是str,所以要转码
    22         f.write(file_content)
    23 #   获取文章标题
    24 def getTitle(file_content):
    25     linkre=re.search(REX_TITLE,file_content)
    26     if(linkre):
    27         print ('获取文章主题:'+linkre.group(1))
    28         return linkre.group(1)
    29  
    30 #   爬虫用到的两个数据结构,队列和集合
    31 queue=deque()
    32 visited=set()
    33 #   初始化种子链接 
    34 queue.append(BASE_URL)
    35 count=0
    36  
    37 while queue:
    38     url=queue.popleft()  # 队首元素出队
    39     visited |= {url}  # 标记为已访问
    40  
    41     print('已经抓取: '+ str(count)+'   正在抓取 <---  '+url)
    42     count += 1
    43     urlop=urllib2.urlopen(url)
    44 # 只处理html链接
    45     if 'html' not in urlop.headers.getheader('Content-Type'):
    46         continue
    47 # 避免程序异常中止
    48     try:
    49         data=urlop.read()
    50         title=getTitle(data).decode('utf-8');
    51     # 保存文件
    52         saveHtml(title,data)
    53     except:
    54         continue
    55  
    56 # 正则表达式提取页面中所有链接, 并判断是否已经访问过, 然后加入待爬队列
    57     linkre = re.compile(REX_URL)
    58     for sub_link in linkre.findall(data):
    59         sub_url=BASE_URL+sub_link+SUFFIX;
    60 # 已经访问过,不再处理
    61         if sub_url in visited:
    62             pass
    63         else:
    64         # 设置已访问
    65             visited |= {sub_url}
    66         # 加入队列
    67             queue.append(sub_url)
    68             print('join the quene--->  '+sub_url)

    http://blog.csdn.net/wangshihui512/article/details/51100605#python

    22 和 49行 与原文有所出处 如果添加了反而无法执行 可能和编码有关系

  • 相关阅读:
    《当大数据遇见网络:大数据与SDN》
    Internet History, Technology and Security (Week 9)
    Internet History, Technology and Security (Week 8)
    Internet History, Technology and Security (Week 7)
    北京讲座所感---6.14~6.15
    Internet History, Technology and Security (Week 6)
    Internet History, Technology and Security (Week 4)
    Internet History, Technology and Security (Week 3)
    Alpha 事后诸葛亮(团队)
    Alpha答辩总结
  • 原文地址:https://www.cnblogs.com/zhuzhuqwa/p/6391738.html
Copyright © 2011-2022 走看看