Python 实现抓取腾讯新闻文章

 

最近学了一段时间的 Python,研究了下爬虫,在网上看了一些资料,然后自己写了一个抓取腾讯新闻文章的爬虫。

首先说一下抓取思路:

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

2、提取详细页面的 Url:https://news.qq.com/a/20190717/006715.htm。

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

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

以下是实现代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#coding=utf-8
import sys
import urllib2
import re
import os
  
def extract_url(info):
     rege="http://news.qq.com/a/\d{8}/\d{6}.htm"
     re_url = re.findall(rege, info)
     return re_url
  
def extract_sub_web_title(sub_web):
     re_key = "<title>.+</title>"
     title = re.findall(re_key,sub_web)
     return title
  
def extract_sub_web_content(sub_web):
     re_key = "<div id=\"Cnt-Main-Article-QQ\".*</div>"
     content = re.findall(re_key,sub_web)
     return content
  
def filter_tags(htmlstr):
     re_cdata=re.compile('//<!\[CDATA\[[^>]*//\]\]>',re.I) #匹配 CDATA
     re_script=re.compile('<\s*script[^>]*>[^<]*<\s*/\s*script\s*>',re.I)#Script
     re_style=re.compile('<\s*style[^>]*>[^<]*<\s*/\s*style\s*>',re.I)#style
     re_p=re.compile('<P\s*?/?>')#处理换行
     re_h=re.compile('</?\w+[^>]*>')#HTML 标签
     re_comment=re.compile('<!--[^>]*-->')#HTML 注释
     s=re_cdata.sub('',htmlstr)#去掉 CDATA
     s=re_script.sub('',s) #去掉 SCRIPT
     s=re_style.sub('',s)#去掉 style
     s=re_p.sub('\r\n',s)#将<p>转换为换行
     s=re_h.sub('',s) #去掉 HTML 标签
     s=re_comment.sub('',s)#去掉 HTML 注释
     blank_line=re.compile('\n+')#去掉多余的空行
     s=blank_line.sub('\n',s)
     return s
  
#get news
content = urllib2.urlopen('http://news.qq.com').read()
  
#get the url
get_url = extract_url(content)
  
#generate file
f = file('result.txt','w')
 i = 15            # 新闻起始位置,前面几条格式不一致
flag = 30
while True:
     f.write(str(i-14)+"\r\n")
  
     #get the sub web title and content
     sub_web = urllib2.urlopen(get_url[i]).read()
     sub_title = extract_sub_web_title(sub_web)
     sub_content = extract_sub_web_content(sub_web)
  
     #remove html tag
     if sub_title != [] and sub_content != []:
         re_content = filter_tags(sub_title[0]+"\r\n"+sub_content[0])
         f.write(re_content.decode("gb2312").encode("utf-8"))
         f.write("\r\n")
     else:
         flag = flag +1
  
     if i == flag:
         break
  
     i = i + 1
     print "Have finished %d news" %(i-15)
f.close()
posted @   Charles Zhang  阅读(16202)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
点击右上角即可分享
微信分享提示