1. 程式人生 > >python爬蟲(以簡書為例)

python爬蟲(以簡書為例)

split agen jieba分詞 nco spa 數據保存 列表 style regular

1.主題:

簡單爬取簡書中的專題‘’@IT·互聯網“中的文章,爬取信息之後通過jieba分詞生成詞雲並且進行分析;

2.實現過程:

第一步:打開簡書並進入到@IT-互聯網專題

網頁鏈接:https://www.jianshu.com/c/V2CqjW?utm_medium=index-collections&utm_source=desktop

技術分享圖片

通過觀察,我們可以發現網頁中的文章並沒有分頁,而是通過下拉滾動條js生成下一頁

我們可以進入開發者工具觀察得知,每次拉到網頁的最後都會多一條請求,仔細觀察它們之間是存在著一定的規律的

技術分享圖片

技術分享圖片

技術分享圖片

它們都是https://www.jianshu.com/c/V2CqjW?order_by=added_at&page={}這樣的格式,改變的值只是page中的數字,是否這就是我們所需要的頁碼呢,可以通過訪問途中鏈接驗證。

現在我們已經取得所需要的鏈接,便可寫出循環的代碼,

但是我們並不知道具體有多少頁,這時,我們通過觀察網頁以及網頁源碼,可以發現

技術分享圖片

在專題下面有收錄了多少篇文章的字樣,即我們只需要獲取到共有多少篇文章再除以每頁多少篇文章即可得出總頁數。分析源碼可以輕松找到

技術分享圖片

技術分享圖片

然後我們就可以寫出以下代碼來獲取它的頁數

註意,由於網頁的安全性問題,直接使用requests,get(url)是無法獲取到簡書網頁的源碼的,所以我們要加上瀏覽器信息

獲取方法

技術分享圖片

接著,編寫代碼

headers = {
        User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36
}
def getPageN():
    url = https://www.jianshu.com/c/V2CqjW?utm_medium=index-collections&utm_source=desktop
    resp = requests.get(url, headers=headers)
    html_content = resp.text  # 得到網頁內容
    soup = BeautifulSoup(html_content, lxml)  # 開始解析
    info = soup.select(.info)[0].text
    pagenumber
=int(info[info.find(收錄了):].split()[0].lstrip(收錄了).rstrip(篇文章)) a = len(soup.find_all(a, class_=title)) page = pagenumber//a+1 return page

第二步:取出一個文章列表頁的全部文章

觀察網頁源碼可知道每篇文章的具體鏈接是

技術分享圖片

最後通過循環獲得所有文章的鏈接

def getListPage(pageUrl):   
    res = requests.get(pageUrl,headers=headers)
    html_content = res.text  
    soup = BeautifulSoup(html_content, lxml)

    newslist = []
    for i in range(len(soup.find_all(a, class_=title))):
        Url = soup.find_all(a, class_=title)[i].attrs[href]
        newsUrl = "https://www.jianshu.com" + Url
        newslist.append(getNewsDetail(newsUrl))

    return(newslist)

第三步:獲得一篇文章的全部內容,並進行分析

def getNewsDetail(newsUrl):   #一篇文章的全部內容
    resd = requests.get(newsUrl,headers=headers)
    html_content = resd.text
    soupd = BeautifulSoup(html_content, lxml)

    news = {}
    news[標題] = soupd.select(.title)[0].text
    news[作者] = soupd.select(.name)[0].text
    news[時間] = datetime.strptime(soupd.select(.publish-time)[0].text.rstrip(*), %Y.%m.%d %H:%M)
    news[字數] = soupd.select(.wordage)[0].text.lstrip(字數 )
    # news[‘內容‘] = soupd.select(‘.show-content-free‘)[0].text.strip()
    news[鏈接] = newsUrl
    content= soupd.select(.show-content-free)[0].text.strip()
    writeNewsDetail(content)
    return(news)

到這裏,基本的爬取工作已經完成了

3.把數據保存成文本:

def writeNewsDetail(content):
    f = open(content.txt,a,encoding=utf-8)
    f.write(content)
    f.close()

技術分享圖片

以及生成excel表格

import pandas
df = pandas.DataFrame(newstotal)
df.to_excel(簡書數據.xlsx)

技術分享圖片

4.生成詞雲:

file = codecs.open(content.txt, r, utf-8)
image=np.array(Image.open(ditu.jpg))
font=rC:\Windows\Fonts\AdobeHeitiStd-Regular.otf
word=file.read()
#去掉英文,保留中文
resultword=re.sub("[A-Za-z0-9\[\`\~\!\@\#\$\^\&\*\(\)\=\|\{\}\‘\:\;\‘\,\[\]\.\<\>\/\?\~\!\@\#\\\&\*\%]", "",word)
wordlist_after_jieba = jieba.cut(resultword, cut_all = True)

wl_space_split = " ".join(wordlist_after_jieba)

# 設置停用詞
stopwords = set(STOPWORDS)
stopwords.add("一個")
my_wordcloud = WordCloud(font_path=font,mask=image,stopwords=stopwords,background_color=white,max_words = 2000,max_font_size = 100,random_state=50).generate(wl_space_split)
#根據圖片生成詞雲
iamge_colors = ImageColorGenerator(image)
#my_wordcloud.recolor(color_func = iamge_colors)
#顯示生成的詞雲
plt.imshow(my_wordcloud)
plt.axis("off")
plt.show()
#保存生成的圖片,當關閉圖片時才會生效,中斷程序不會保存
my_wordcloud.to_file(result.jpg)

生成的詞雲圖片:

技術分享圖片

技術分享圖片

5.遇到的問題:

1、文章總頁數只能爬取到200頁,再繼續爬取下去出現的只是重復的數據,沒有找到解決辦法,但是對於練習而言,兩百頁的數據也足夠了。

2、安裝詞雲遇到的問題

技術分享圖片

解決辦法:

通過閱讀其他博客尋找到的解決辦法

在https://www.lfd.uci.edu/~gohlke/pythonlibs/#wordcloud 中下載對應python版本和window 32/64位版本

技術分享圖片

因為我電腦的python版本是3.6,32位系統,所以下載 wordcloud?1.4.1?cp36?cp36m?win32.whl文件並把文件放在D盤

cmd命令行進入對應wordcloud安裝路徑,我是放在F盤,所以進入D:輸入 pip install wordcloud?1.4.1?cp36?cp36m?win32.whl 即可成功導入

最後,手動為pycharm添加lib,手動找到wordCloud安裝路徑,復制到C:\User\ - \PycharmProjects\**\verv\lib 中即可,(**表示自己創建的項目名字)

技術分享圖片

6.完整代碼:

import re
import requests
import pandas
from bs4 import BeautifulSoup
from datetime import datetime
import jieba
import matplotlib.pyplot as plt
from wordcloud import WordCloud, STOPWORDS, ImageColorGenerator
import codecs
import numpy as np
from PIL import Image

headers = {
        User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36
    }

def writeNewsDetail(content):
    f = open(content.txt,a,encoding=utf-8)
    f.write(content)
    f.close()

def getNewsDetail(newsUrl):   #一篇文章的全部內容
    resd = requests.get(newsUrl,headers=headers)
    html_content = resd.text
    soupd = BeautifulSoup(html_content, lxml)

    news = {}
    news[標題] = soupd.select(.title)[0].text
    news[作者] = soupd.select(.name)[0].text
    news[時間] = datetime.strptime(soupd.select(.publish-time)[0].text.rstrip(*), %Y.%m.%d %H:%M)
    news[字數] = soupd.select(.wordage)[0].text.lstrip(字數 )
    # news[‘內容‘] = soupd.select(‘.show-content-free‘)[0].text.strip()
    news[鏈接] = newsUrl
    content= soupd.select(.show-content-free)[0].text.strip()
    writeNewsDetail(content)
    return(news)

def getListPage(pageUrl):
    res = requests.get(pageUrl,headers=headers)
    html_content = res.text
    soup = BeautifulSoup(html_content, lxml)

    newslist = []
    for i in range(len(soup.find_all(a, class_=title))):
        Url = soup.find_all(a, class_=title)[i].attrs[href]
        newsUrl = "https://www.jianshu.com" + Url
        newslist.append(getNewsDetail(newsUrl))

    return(newslist)


def getPageN():
    url = https://www.jianshu.com/c/V2CqjW?utm_medium=index-collections&utm_source=desktop
    resp = requests.get(url, headers=headers)
    html_content = resp.text  # 得到網頁內容
    soup = BeautifulSoup(html_content, lxml)  # 開始解析
    info = soup.select(.info)[0].text
    pagenumber=int(info[info.find(收錄了):].split()[0].lstrip(收錄了).rstrip(篇文章))
    a = len(soup.find_all(a, class_=title))
    page = pagenumber//a+1
    return page

newstotal = []
firstPageUrl=https://www.jianshu.com/c/V2CqjW?utm_medium=index-collections&utm_source=desktop
newstotal.extend(getListPage(firstPageUrl))
for i in range(2,201):
    listPageUrl=https://www.jianshu.com/c/V2CqjW?order_by=added_at&page={}.format(i)
    newstotal.extend(getListPage(listPageUrl))

df = pandas.DataFrame(newstotal)
df.to_excel(簡書數據.xlsx)

file = codecs.open(content.txt, r, utf-8)
image=np.array(Image.open(ditu.jpg))
font=rC:\Windows\Fonts\AdobeHeitiStd-Regular.otf
word=file.read()
#去掉英文,保留中文
resultword=re.sub("[A-Za-z0-9\[\`\~\!\@\#\$\^\&\*\(\)\=\|\{\}\‘\:\;\‘\,\[\]\.\<\>\/\?\~\!\@\#\\\&\*\%]", "",word)
wordlist_after_jieba = jieba.cut(resultword, cut_all = True)

wl_space_split = " ".join(wordlist_after_jieba)

# 設置停用詞
stopwords = set(STOPWORDS)
stopwords.add("一個")
my_wordcloud = WordCloud(font_path=font,mask=image,stopwords=stopwords,background_color=white,max_words = 2000,max_font_size = 100,random_state=50).generate(wl_space_split)
#根據圖片生成詞雲
iamge_colors = ImageColorGenerator(image)
#my_wordcloud.recolor(color_func = iamge_colors)
#顯示生成的詞雲
plt.imshow(my_wordcloud)
plt.axis("off")
plt.show()
#保存生成的圖片,當關閉圖片時才會生效,中斷程序不會保存
my_wordcloud.to_file(result.jpg)

7.數據分析與結論

通過對爬取的數據分析可以發現:產品、用戶、數據、信息、分析、平臺、市場、服務、應用、價值、內容等關鍵詞尤為重要。

這些關鍵詞也是互聯網行業中值得註意的,例如通過數據信息等分析人們的需求等,是當今互聯網行業中重要的一環,

所以通過爬蟲獲取信息進行有效分析也顯得尤為重要。

python爬蟲(以簡書為例)