1. 將新聞的正文內容儲存到文字檔案。
f = open(「content.txt」, 'a', encoding='
utf-8')
f.write(content)
f.close()
2. 將新聞資料結構化為字典的列表:
#獲取新聞詳情
defgetnewdetail(url):
resd =requests.get(url)
resd.encoding = '
utf-8
'soupd = beautifulsoup(resd.text, '
html.parser')
#單條新聞的詳情
news ={}
news[
'title
'] = soupd.select('
.show-title
')[0].text
info = soupd.select('
.show-info
')[0].text
t = soupd.select('
.show-info
')[0].text[0:24].lstrip('')
news['dt
'] = datetime.strptime(t, '
%y-%m-%d %h:%m:%s')
if info.find('
') >0:
news[
'source
'] = info[info.find('
'):].split()[0].lstrip('')
else
: news[
'source
'] = '
none
'if info.find('
') >0:
news[
'author
'] = info[info.find('
'):].split()[0].lstrip('')
else
: news[
'author
'] = '
none
'news[
'content
'] = soupd.select('
.show-content
')[0].text.strip()
writenewsdetail(news[
'content'])
news[
'click
'] =getclickcount(url)
news[
'url
'] =url
return (news)
defgetlistpage(pageurl):
res =requests.get(pageurl)
res.encoding = '
utf-8
'soup = beautifulsoup(res.text,'
html.parser')
newslist =
for news in soup.select('li'
):
if len(news.select('
.news-list-title
')) >0:
#獲取每條新聞鏈結
a = news.select('
a')[0].attrs['
href']
#呼叫函式獲取新聞詳情頁的內容
#乙個列表頁所有單條新聞彙總
(newslist)
return (newslist)
newstotal =fristpage = '
'#第一頁新聞彙總列表
newstotal.extend(getlistpage(fristpage))
#獲取每頁新聞的鏈結
n =getpagen()
for i in range(2,n):
pageurl = '
{}.html
'.format(i)
#所有列表頁的所有新聞彙總列表
newstotal.extend(getlistpage(pageurl))
3. 安裝pandas,用pandas.dataframe(newstotal),建立乙個dataframe物件df.
import pandas
df = pandas.dataframe(newstotal)
4. 通過df將提取的資料儲存到csv或excel 檔案。
df.to_excel('gzccnews.xlsx
')
5. 用pandas提供的函式和方法進行資料分析:
print(df[['clicks
', '
title
', '
source
']].head(6))
print(df[(df['clicks
'] > 3000) & (df['
source
'] == '
學校綜合辦
')])
info = ['國際學院
','學生工作處']
print(df[df['
source
'].isin(info)])
資料結構化與儲存
1.將新聞的正文內容儲存到文字檔案。soup beautifulsoup res.text,html.parser content soup.select show content 0 text f open news.txt w encoding utf 8 f.write content f.c...
資料結構化與儲存
作業是 同學的,因為沒有對新聞資訊做提取,所有無法新增新聞資訊到字典。已練習pandas庫的相關使用方法,匯出excel檔案。ps 自己的 會盡快修改!import requests from bs4 import beautifulsoup from datetime import datetim...
資料結構化與儲存
1.將新聞的正文內容儲存到文字檔案。newscontent soup.select show content 0 text f open news.txt w f.write newscontent f open news.txt r print f.read 3.安裝pandas,用pandas....