1. 將新聞的正文內容儲存到文字檔案。
def writenewsdetail(content):2. 將新聞資料結構化為字典的列表:f = open('gzccnews.txt', 'a',encoding='utf-8')
f.write(content)
f.close()
import requestsfrom bs4 import beautifulsoup
from datetime import datetime
import re
import pandas
def writenewsdetail(content):
f = open('gzccnews.txt', 'a',encoding='utf-8')
f.write(content)
f.close()
def getclickcount(newsurl): #一篇新聞的點選次數
newid = re.search('\_(.*).html', newsurl).group(1).split('/')[1]
clickurl = "".format(newid)
return (int(requests.get(clickurl).text.split('.html')[-1].lstrip("('").rstrip("');")))
def getnewsdetail(newsurl): #一篇新聞的全部資訊
resd = requests.get(newsurl)
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
else:
news['source'] = 'none'
news['content'] = soupd.select('.show-content')[0].text.strip()
writenewsdetail(news['content'])
news['click'] = getclickcount(newsurl)
news['newsurl'] = newsurl
return(news)
def getlistpage(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:
newsurl = news.select('a')[0].attrs['href'] # 鏈結
return(newslist)
def getpagen(): # 新聞列表頁的總頁數
res = requests.get('')
res.encoding = 'utf-8'
soup = beautifulsoup(res.text, 'html.parser')
n = int(soup.select('.a1')[0].text.rstrip('條'))
3. 安裝pandas,用pandas.dataframe(newstotal),建立乙個dataframe物件df.
df = pandas.dataframe(newstotal)4. 通過df將提取的資料儲存到csv或excel 檔案。print(df)
5. 用pandas提供的函式和方法進行資料分析:
資料結構化與儲存
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....