python大作业爬虫_爬虫大作业
1.選一個(gè)自己感興趣的主題(所有人不能雷同)。
2.用python 編寫(xiě)爬蟲(chóng)程序,從網(wǎng)絡(luò)上爬取相關(guān)主題的數(shù)據(jù)。
3.對(duì)爬了的數(shù)據(jù)進(jìn)行文本分析,生成詞云。
4.對(duì)文本分析結(jié)果進(jìn)行解釋說(shuō)明。
5.寫(xiě)一篇完整的博客,描述上述實(shí)現(xiàn)過(guò)程、遇到的問(wèn)題及解決辦法、數(shù)據(jù)分析思想及結(jié)論。
6.最后提交爬取的全部數(shù)據(jù)、爬蟲(chóng)及數(shù)據(jù)分析源代碼。
1、開(kāi)發(fā)環(huán)境
編程語(yǔ)言:Python3.6
代碼運(yùn)行工具:pycham
依賴庫(kù):Requests,BeautifulSoup,wordcloud,re,jieba等
2、開(kāi)發(fā)軟件已經(jīng)第三方庫(kù)的安裝
由于開(kāi)發(fā)軟件的安裝流程網(wǎng)上都有比較詳細(xì)的介紹,所以在這里只是給出參考網(wǎng)站,具體講一下的是第三方庫(kù)的安裝
Python3.6的安裝教程參照(https://jingyan.baidu.com/article/e9fb46e1502c5a7520f76640.html)
pycham的安裝教程參照(https://jingyan.baidu.com/article/90895e0f28a32064ec6b0bc7.html)
在windows上安裝python依賴庫(kù)非常簡(jiǎn)單,語(yǔ)法如下:pip install PackageNamePackageName指的是你安裝的依賴包名稱。
例如安裝requests依賴包可以這樣安裝:pip install requests
但是以上的安裝依賴包的方法用于wordcloud依賴包的安裝是不行的,軟件會(huì)報(bào)錯(cuò)的。我上網(wǎng)找了一下解決的方法有兩個(gè)比較可行的。
第一個(gè)是去https://www.lfd.uci.edu/~gohlke/pythonlibs/#wordcloud選擇合適的版本下載whl文件,注意的是,cp指的是系統(tǒng)上安裝的python版本,32或者64表示安裝的python版本是32位或者64位的,而不是你電腦的操作系統(tǒng)多少位的
下載完成后打開(kāi)cmd運(yùn)行,切換到指定目錄運(yùn)行,代碼如下:
pip install wordcloud-1.4.1-cp36-cp36m-win32.whl
pip install wordcloud
其中wordcloud-1.4.1-cp36-cp36m-win32.whl是你下載的whl文件的名字或者說(shuō)是你下載的whl 的版本。
第二個(gè)是去網(wǎng)站下載一個(gè)vs2017可以解決這個(gè)問(wèn)題,不過(guò)這個(gè)軟件太大了有幾個(gè)G,下載什么的太浪費(fèi)時(shí)間,不過(guò)在第一種情況你還不能解決wordcloud不能安裝的問(wèn)題也可以使用第二種
參考網(wǎng)站https://jingyan.baidu.com/article/597a06433b992e312b524384.html
要注意的是你使用的依賴包一定要都下載了,不然使用不了,特別是生成詞云是時(shí)候使用到的jieba依賴包
3、爬蟲(chóng)程序的編輯以及生成詞云
爬取廣州商學(xué)院校園網(wǎng)新聞
# coding: utf-8
import re
import requests
from bs4 import BeautifulSoup
from datetime import datetime
def getClickCount(r):
s = re.findall('\_(.*).html', r)[0].split('/')[-1]
res = requests.get('http://oa.gzcc.cn/api.php?op=count&id={}&modelid=80'.format(s))
return int(res.text.split('.html')[-1].lstrip("('").rstrip("');"))
def getNewsDetail(newsUrl): # 一篇新聞的全部?jī)?nèi)容
resd = requests.get(newsUrl)
resd.encoding = 'utf-8'
soupd = BeautifulSoup(resd.text, 'html.parser') # 打開(kāi)新聞詳情并解析
news = {}
news['title'] = soupd.select('.show-title')[0].text
info = soupd.select('.show-info')[0].text
news['dt'] = datetime.strptime(info.lstrip('發(fā)布時(shí)間:')[0:19], '%Y-%m-%d %H:%M:%S')
if info.find('來(lái)源:') > 0:
news['source'] = info[info.find('來(lái)源:'):].split()[0].lstrip('來(lái)源:')
else:
news['source'] = 'none'
news['content'] = soupd.select('.show-content')[0].text.strip()
news['click'] = getClickCount(newsUrl)
news['newsUrl'] = newsUrl
return (news)
def getListPage(pageUrl): # 9. 取出一個(gè)新聞列表頁(yè)的全部新聞 包裝成函數(shù)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']
newslist.append(getNewsDetail(newsUrl))
return (newslist)
def getPageN():
res = requests.get('http://news.gzcc.cn/html/xiaoyuanxinwen/')
res.encoding = 'utf-8'
soup = BeautifulSoup(res.text, 'html.parser')
pagenumber = int(soup.select('.a1')[0].text.rstrip('條'))
page = pagenumber // 10 + 1
return page
newstotal = []
firstPageUrl = 'http://news.gzcc.cn/html/xiaoyuanxinwen/'
newstotal.extend(getListPage(firstPageUrl))
n = getPageN()
# f = open('gzccnews.txt','a',encoding='utf-8')
for i in range(n, n + 1):
listPageUrl = 'http://news.gzcc.cn/html/xiaoyuanxinwen/{}.html'.format(i)
newstotal.extend(getListPage(listPageUrl))
for news in newstotal:
print(news)
import pandas
df = pandas.DataFrame(newstotal)
df.to_excel('gzccnews.xlsx')
# fo = open('output.txt', "ab+")
# # 以二進(jìn)制寫(xiě)入章節(jié)題目 需要轉(zhuǎn)換為utf-8編碼,否則會(huì)出現(xiàn)亂碼
# fo.write(('\r' + + '\r\n').encode('UTF-8'))
# # 以二進(jìn)制寫(xiě)入章節(jié)內(nèi)容
# fo.write(().encode('UTF-8'))
# fo.close()
選取想要生成詞云圖片(可以根據(jù)你自己的喜歡更換你的選擇)
生成詞云
#coding:utf-8
import matplotlib.pyplot as plt
from wordcloud import WordCloud,ImageColorGenerator,STOPWORDS
import jieba
import numpy as np
from PIL import Image
#讀入背景圖片
abel_mask = np.array(Image.open("gui.jpg"))
#讀取要生成詞云的文件
text_from_file_with_apath = open('output.txt',encoding='utf-8').read()
#通過(guò)jieba分詞進(jìn)行分詞并通過(guò)空格分隔
wordlist_after_jieba = jieba.cut(text_from_file_with_apath, cut_all = True)
wl_space_split = " ".join(wordlist_after_jieba)
#my_wordcloud = WordCloud().generate(wl_space_split) 默認(rèn)構(gòu)造函數(shù)
my_wordcloud = WordCloud(
background_color='white', # 設(shè)置背景顏色
mask = abel_mask, # 設(shè)置背景圖片
max_words = 800, # 設(shè)置最大現(xiàn)實(shí)的字?jǐn)?shù)
stopwords = {}.fromkeys(['學(xué)院', '廣州','法律','教師','新生','會(huì)議','主持','書(shū)記','學(xué)生']), # 設(shè)置停用詞
font_path = 'C:/Users/Windows/fonts/simkai.ttf',# 設(shè)置字體格式,如不設(shè)置顯示不了中文
max_font_size = 50, # 設(shè)置字體最大值
random_state = 30, # 設(shè)置有多少種隨機(jī)生成狀態(tài),即有多少種配色方案
scale=.5
).generate(wl_space_split)
# 根據(jù)圖片生成詞云顏色
image_colors = ImageColorGenerator(abel_mask)
# 以下代碼顯示圖片
plt.imshow(my_wordcloud)
plt.axis("off")
plt.show()
生成詞云后的圖片
總結(jié)
以上是生活随笔為你收集整理的python大作业爬虫_爬虫大作业的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 蓝牙耳机芯片检测软件_安凯微推出TWS真
- 下一篇: 怎么引jsp包_电机引接线的制作流程防护