【Python網絡爬蟲三】 爬取網頁新聞

學弟又一個天然語言處理的項目,須要在網上爬一些文章,而後進行分詞,恰好牛客這周的是從一個html中找到正文,就實踐了一下。寫了一個爬門戶網站新聞的程序html

 

需求:

從門戶網站爬取新聞,將新聞標題,做者,時間,內容保存到本地txt中。node

 

用到的python模塊:python

1 import re  # 正則表達式
2 import bs4  # Beautiful Soup 4 解析模塊
3 import urllib2  # 網絡訪問模塊
4 import News   #本身定義的新聞結構
5 import codecs  #解決編碼問題的關鍵 ,使用codecs.open打開文件
6 import sys   #1解決不一樣頁面編碼問題

其中bs4須要本身裝一下,安裝方法能夠參考:Windows命令行下pip安裝python whl包正則表達式

 

程序:

 1 #coding=utf-8
 2 import re  # 正則表達式
 3 import bs4  # Beautiful Soup 4 解析模塊
 4 import urllib2  # 網絡訪問模塊
 5 import News   #本身定義的新聞結構
 6 import codecs  #解決編碼問題的關鍵 ,使用codecs.open打開文件
 7 import sys   #1解決不一樣頁面編碼問題
 8 
 9 reload(sys)                         # 2
10 sys.setdefaultencoding('utf-8')     # 3
11 
12 # 從首頁獲取全部連接
13 def GetAllUrl(home):
14     html = urllib2.urlopen(home).read().decode('utf8')
15     soup = bs4.BeautifulSoup(html, 'html.parser')
16     pattern = 'http://\w+\.baijia\.baidu\.com/article/\w+'
17     links = soup.find_all('a', href=re.compile(pattern))
18     for link in links:
19         url_set.add(link['href'])
20 
21 def GetNews(url):
22     global NewsCount,MaxNewsCount  #全局記錄新聞數量
23     while len(url_set) != 0:
24         try:
25             # 獲取連接
26             url = url_set.pop()
27             url_old.add(url)
28 
29             # 獲取代碼
30             html = urllib2.urlopen(url).read().decode('utf8')
31 
32             # 解析
33             soup = bs4.BeautifulSoup(html, 'html.parser')
34             pattern = 'http://\w+\.baijia\.baidu\.com/article/\w+'  # 連接匹配規則
35             links = soup.find_all('a', href=re.compile(pattern))
36 
37             # 獲取URL
38             for link in links:
39                 if link['href'] not in url_old:
40                     url_set.add(link['href'])
41 
42                     # 獲取信息
43                     article = News.News()
44                     article.url = url  # URL信息
45                     page = soup.find('div', {'id': 'page'})
46                     article.title = page.find('h1').get_text()  # 標題信息
47                     info = page.find('div', {'class': 'article-info'})
48                     article.author = info.find('a', {'class': 'name'}).get_text()  # 做者信息
49                     article.date = info.find('span', {'class': 'time'}).get_text()  # 日期信息
50                     article.about = page.find('blockquote').get_text()
51                     pnode = page.find('div', {'class': 'article-detail'}).find_all('p')
52                     article.content = ''
53                     for node in pnode:  # 獲取文章段落
54                         article.content += node.get_text() + '\n'  # 追加段落信息
55 
56                     SaveNews(article)
57 
58                     print NewsCount
59                     break
60         except Exception as e:
61             print(e)
62             continue
63         else:
64             print(article.title)
65             NewsCount+=1
66         finally:
67             # 判斷數據是否收集完成
68             if NewsCount == MaxNewsCount:
69                 break
70 
71 def SaveNews(Object):
72     file.write(""+Object.title+""+"\t")
73     file.write(Object.author+"\t"+Object.date+"\n")
74     file.write(Object.content+"\n"+"\n")
75 
76 url_set = set()  # url集合
77 url_old = set()  # 爬過的url集合
78 
79 NewsCount = 0
80 MaxNewsCount=3
81 
82 home = 'http://baijia.baidu.com/'  # 起始位置
83 
84 GetAllUrl(home)
85 
86 file=codecs.open("D:\\test.txt","a+") #文件操做
87 
88 for url in url_set:
89     GetNews(url)
90     # 判斷數據是否收集完成
91     if NewsCount == MaxNewsCount:
92         break
93 
94 file.close()

新聞文章結構網絡

 1 #coding: utf-8
 2 # 文章類定義
 3 class News(object):
 4     def __init__(self):
 5         self.url = None
 6         self.title = None
 7         self.author = None
 8         self.date = None
 9         self.about = None
10         self.content = None

 

對爬取的文章數量就行統計。網站

相關文章
相關標籤/搜索