好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

Python 实现腾讯新闻抓取

Python 实现腾讯新闻抓取

随笔- 3  文章- 0  评论- 3 

Python 实现腾讯新闻抓取

 

思路:

1.抓取腾讯新闻列表页面:  http://news.qq.com/

2.提取详细页面的url: http://news.qq.com/a/20120814/000070.htm

3.在详细页中提取新闻标题和内容

4.去除提取内容中的html标签,生成txt文档

 代码:

  1   #  coding=utf-8 
  2   import   sys
   3   import   urllib2
   4   import   re
   5   import   os
   6  
  7   def   extract_url(info):
   8      rege= "  http://news.qq.com/a/\d{8}/\d{6}.htm  " 
  9      re_url =  re.findall(rege, info)
  10       return   re_url
  11  
 12   def   extract_sub_web_title(sub_web):
  13      re_key =  "  <title>.+</title>  " 
 14      title =  re.findall(re_key,sub_web)
  15       return   title
  16  
 17   def   extract_sub_web_content(sub_web):
  18      re_key =  "  <div id=\"Cnt-Main-Article-QQ\".*</div>  " 
 19      content =  re.findall(re_key,sub_web)
  20       return   content
  21  
 22   def   filter_tags(htmlstr):
  23      re_cdata=re.compile( '  //<!\[CDATA\[[^>]*//\]\]>  ' ,re.I)  #  匹配CDATA 
 24      re_script=re.compile( '  <\s*script[^>]*>[^<]*<\s*/\s*script\s*>  ' ,re.I) #  Script 
 25      re_style=re.compile( '  <\s*style[^>]*>[^<]*<\s*/\s*style\s*>  ' ,re.I) #  style 
 26      re_p=re.compile( '  <P\s*?/?>  ' ) #  处理换行 
 27      re_h=re.compile( '  </?\w+[^>]*>  ' ) #  HTML标签 
 28      re_comment=re.compile( '  <!--[^>]*-->  ' ) #  HTML注释 
 29      s=re_cdata.sub( '' ,htmlstr) #  去掉CDATA 
 30      s=re_script.sub( '' ,s)  #  去掉SCRIPT 
 31      s=re_style.sub( '' ,s) #  去掉style 
 32      s=re_p.sub( '  \r\n  ' ,s) #  将<p>转换为换行 
 33      s=re_h.sub( '' ,s)  #  去掉HTML 标签 
 34      s=re_comment.sub( '' ,s) #  去掉HTML注释   
 35      blank_line=re.compile( '  \n+  ' ) #  去掉多余的空行 
 36      s=blank_line.sub( '  \n  '  ,s)
  37       return   s
  38  
 39   #  get news 
 40  content = urllib2.urlopen( '  http://news.qq.com  '  ).read()
  41  
 42   #  get the url 
 43  get_url =  extract_url(content)
  44  
 45   #  generate file 
 46  f = file( '  result.txt  ' , '  w  '  )
  47  i = 15             #  新闻起始位置,前面几条格式不一致 
 48  flag = 30
 49   while   True:
  50      f.write(str(i-14)+ "  \r\n  "  )
  51      
 52       #  get the sub web title and content 
 53      sub_web =  urllib2.urlopen(get_url[i]).read()
  54      sub_title =  extract_sub_web_title(sub_web)
  55      sub_content =  extract_sub_web_content(sub_web)
  56  
 57       #  remove html tag 
 58       if  sub_title != []  and  sub_content !=  []:
  59          re_content = filter_tags(sub_title[0]+ "  \r\n  " + sub_content[0])
  60          f.write(re_content.decode( "  gb2312  " ).encode( "  utf-8  "  ))
  61          f.write( "  \r\n  "  )
  62       else  :
  63          flag = flag +1
 64      
 65       if  i ==  flag:
  66           break 
 67   
 68      i = i + 1
 69       print   "  Have finished %d news  "  %(i-15 )
  70  f.close()

说明:

 urllib2 模块:进行网页内容抓取
re模块:进行正则表达式提取
decode( " gb2312 " ).encode( " utf-8 " ):因为提取网页的编码是gb2312所以要解码后在编码到utf-8显示
filter_tags :去除提取的内容的html标签,baidu可以找到这个函数,又修改了下

 

调试中遇到的问题:

1.Table 'polls.django_admin_log' doesn't exist
今天没事调试一下DJANGO框架的时候官方的例子出现如下错误在这记录一下吧~!

原因:数据库未同步

解决方法:python manage.py syncdb

 

2.IndentationError: unexpected indent python

原因:缩进错误

解决方法:删除缩进,统一用tab,注意tab设置为4空格

 

3.[Errno 9] Bad file descriptor

原因:读文件用了 fileopen(filename,”w”)

解决方法:fileopen(filename,”r”)

 

4.  IndexError: list index out of range

原因:for i in range(len(List))

              del len(List)

         在动态删除List过程中越界

解决办法:不要动态删除,采用两个List操作

 

 5.TypeError: expected string or buffer
原因:re_h=re.compile('</?\w+[^>]*>')
         s=re_h.sub('',str)

         传入的str是list变量导致出错

解决办法:传入str类型变量

附:我的vim设置 

要在 ~ 目录下(即用户根目录)新建 .vimrc,这样对其它用户不影响

 syntax on
set fileencodings =utf-8,cp936,big5,euc-jp,euc-kr,latin1,ucs- bom 
set fileencodings =utf-8 ,gbk 
set ambiwidth = double
set langmenu =zh_CN.UTF-8 
set mouse = a
set nu
set foldmethod = indent
set sw =4 
set ts =4 
set smarttab
set spell
set tw =78 
set lbr
set fo += mB
set t_Co =256          // 颜色覆盖问题,默认的效果太差
colorscheme  default    //配色方案

 

分类:  python

作者: Leo_wl

    

出处: http://www.cnblogs.com/Leo_wl/

    

本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

版权信息

查看更多关于Python 实现腾讯新闻抓取的详细内容...

  阅读:39次