1. 將新聞的正文內容保存到文本文件。html
f = open(filename, 'a', encoding='utf-8') f.write(content) f.close()
2. 將新聞數據結構化爲字典的列表:python
(1)單條新聞的詳情-->字典news數據結構
def getNewDetail(a): newsdict={} resd = requests.get(a) resd.encoding = 'utf-8' soupd = BeautifulSoup(resd.text, 'html.parser') newsdict['title'] = soupd.select('.show-title')[0].text info = soupd.select('.show-info')[0].text d= info.lstrip('發佈時間:')[:19] newsdict['a']=a newsdict['dateTime'] = datetime.strptime(d, '%Y-%m-%d %H:%M:%S') newsdict['author'] = info[info.find('做者:'):].split()[0].lstrip('做者:') newsdict['source'] = info[info.find('來源:'):].split()[0].lstrip('來源:') newsdict['photo'] = info[info.find('攝影:'):].split()[0].lstrip('攝影:') newsdict['clickcount'] = getClickCount(a) return newsdict
(2)一個列表頁全部單條新聞彙總-->列表newsls.append(news)app
def listPage(pageUrl): newsls = [] res = requests.get(pageUrl) # 返回response對象 res.encoding = 'utf-8' soup = BeautifulSoup(res.text, 'html.parser') for news in soup.select('li'): if len(news.select('.news-list-title')) > 0: a = news.select('a')[0].attrs['href'] # 連接 newsls.append(getNewDetail(a)) return newsls
(3)全部列表頁的全部新聞彙總列表newstotal.extend(newsls)函數
def getpagelist(path): res = requests.get(path) # 返回response對象 res.encoding = 'utf-8' soup = BeautifulSoup(res.text, 'html.parser') newsnum = int(soup.select('.a1')[0].text.rstrip('條')) # 新聞總條數 if (newsnum % 10 == 0): totalpage = newsnum // 10 else: totalpage = newsnum // 10 + 1 # 新聞總頁數 for i in range(1, totalpage): pageUrl = path + '{}.html'.format(i) newstotal.append(listPage(pageUrl))
3. 安裝pandas,用pandas.DataFrame(newstotal),建立一個DataFrame對象df.excel
import pandas df = pandas.DataFrame(newstotal)
4. 經過df將提取的數據保存到csv或excel 文件。orm
df.to_excel('gzccnews.xlsx')
5. 用pandas提供的函數和方法進行數據分析:htm
(1)提取包含點擊次數、標題、來源的前6行數據對象
df[['clickcount', 'title', 'source']].head(6) print(df[['clickcount', 'title', 'source']].head(6))
(2)提取‘學校綜合辦’發佈的,‘點擊次數’超過3000的新聞。blog
df[(df['clickcount'] > 3000) & (df['source'] == '學校綜合辦')] print(df[(df['clickcount'] > 3000) & (df['source'] == '學校綜合辦')])
(3)提取'國際學院'和'學生工做處'發佈的新聞。
soulist = ['國際學院', '學生工做處'] print(df[df['source'].isin(soulist)]