zoukankan      html  css  js  c++  java
  • python抓取

    我要抓取奥巴马每周的演讲内容http://www.putclub.com/html/radio/VOA/presidentspeech/index.html

    如果手动提取,就需要一个个点进去,再复制保存,非常麻烦。

    那有没有一步到位的方法呢,用python这种强大的语言就能快速实现。

    首先我们看看这网页的源码

    可以发现,我们要的信息就在这样一小条url中。

    更具体点说,就是我们要遍历每个类似http://www.putclub.com/html/radio/VOA/presidentspeech/2014/0928/91326.html这样的网址,而这网址需要从上面的网页中提取。

    好,开始写代码

    首先打开这个目录页,保存在content

    [python] view plain copy
     
    1. import sys,urllib  
    2. url="http://www.putclub.com/html/radio/VOA/presidentspeech/index.html"  
    3. wp = urllib.urlopen(url)  
    4. print "start download..."  
    5. content = wp.read()  

    下面要提取出每一篇演讲的内容

    具体思路是搜索“center_box”之后,每个“href=”和“target”之间的内容。为什么是这两个之间,请看网页源码。

    得到的就是每一篇的url,再在前面加上www.putclub.com就是每一篇文章的网址啦

    [html] view plain copy
     
    1. print content.count("center_box")  
    2. index =  content.find("center_box")  
    3. content=content[content.find("center_box")+1:]  
    4. content=content[content.find("href=")+7:content.find("target")-2]  
    5. filename = content  
    6. url ="http://www.putclub.com/"+content  
    7. print content  
    8. print url  
    9. wp = urllib.urlopen(url)  
    10. print "start download..."  
    11. content = wp.read()  

    有了文章内容的url后,同样的方法筛选内容。

    [python] view plain copy
     
    1. #print content  
    2. print content.count("<div class="content"")  
    3. #content = content[content.find("<div class="content""):]  
    4. content = content[content.find("<!--info end------->"):]  
    5. content = content[:content.find("<div class="dede_pages"")-1]  
    6. filename = filename[filename.find("presidentspeech")+len("presidentspeech/"):]  

    最后再保存并打印

    [python] view plain copy
     
    1. filename = filename.replace('/',"-",filename.count("/"))  
    2. fp = open(filename,"w+")  
    3. fp.write(content)  
    4. fp.close()  
    5. print content  


    OK,大功告成!保存成.pyw文件,以后只需双击就直接保存下了obama每周演讲内容~

  • 相关阅读:
    [UGUI]事件机制
    [C#]CompareTo
    [Unity算法]交换排序(二):快速排序
    [Unity算法]交换排序(一):冒泡排序
    [Lua]string(二):string.sub处理中文
    [Lua]string(一):string库
    [Unity热更新]LuaFramework14.打包、加载和卸载策略
    [Unity热更新]LuaFramework13.事件派发
    数仓day01
    大数据学习day39----数据仓库02------1. log4j 2. 父子maven工程(子spring项目的创建)3.项目开发(埋点日志预处理-json数据解析、清洗过滤、数据集成实现、uid回补)
  • 原文地址:https://www.cnblogs.com/babyfei/p/6992235.html
Copyright © 2011-2022 走看看