抓取《統計學習方法》前100條評論

  • 2020 年 2 月 19 日
  • 筆記

今天看完大壯老師《用Python玩轉數據》的網路數據獲取,決定來上手操作一下。就嘗試抓取業界享譽好評《統計學習方法》的前100條評論,計算出平均得分。

1. 把python添加為環境變數

 PATH=PATH;C:UsersAdministratorAppDataLocalProgramsPythonPython36-32  

(這裡 C:UsersAdministratorAppDataLocalProgramsPythonPython36-32 為本機存放python.exe 的位置 )

運行上述命令之後 即可添加python到環境變數

2. 安裝bs4和requests, lxml庫,可以選擇通過pip命令進行安裝。

注意這裡運行pip的時候需要進入pip所在目錄,否則的pip無法進行安裝。

cd C:UsersAdministratorAppDataLocalProgramsPythonPython36-32Scripts

在當前環境下依次輸入

pip install bs4  pip install requests  pip install lxml

就會開始下載bs4 , requests, lxml庫 o( ̄ヘ ̄o#)

3 做好上述準備工作之後,咱們就可以開始在Pycharm環境下編寫code進行抓取數據啦。

在這裡我要提醒兩個地方

1. 一定要加上verify=False這個選項,這樣Requests能忽略對SSL證書的驗證。

r = requests.get('https://book.douban.com/subject/10590856/comments/hot?p=' + str(i+1),verify=False)

否則會出現SSLERROR: HTTPSConnectionPool(host='book.douban.com', port=443): Max retries exceeded with url: /subject/10590856/comments/hot?p=2 (Caused by SSLError(SSLError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:749)'),))

2. Regular Expression

pattern = re.compile('<span class="user-stars allstar(.*?) rating"'),

這裡可以匹配的結果大家可以通過 https://regex101.com/ 進行查詢

4.code

#抓取抓取《統計學習方法》前100條評論    """    @author zhujin    @version python3.6.1    @date 2017/11/25 Saturday    """    import requests, re, time    from bs4 import BeautifulSoup  count = 0  i = 0  sum, count_s = 0, 0    while(count < 100):     try:         r = requests.get('https://book.douban.com/subject/10590856/comments/hot?p=' + str(i+1),verify=False)     except Exception as err:         print(err)         break     soup = BeautifulSoup(r.text, 'lxml')     comments = soup.find_all('p', 'comment-content')     for item in comments:         count = count + 1         print(count, item.string)         if count == 100:             break     pattern = re.compile('<span class="user-stars allstar(.*?) rating"')     p = re.findall(pattern, r.text)     for star in p:         count_s = count_s + 1         sum += int(star)     time.sleep(5)    # delay request from douban's robots.txt     i += 1  if count == 100:         print('the average score of this book is ' + str(sum / count_s))

5.運行上述code,得到的result

1 絕對不適合初學者。在理解了書所涉及的演算法後,可以讀本書。「事兒就這麼個事兒,不解釋」的范,典型的中式思維,精於總結而不精於解釋。有點在於比其它譚浩強類電腦書認真點,每一章都會有論文的出處,可以自己去查。總之,適合回首往事,不適合一見鍾情。 2 標準的中國教材,基本該涉及到的知識點都設計到了,就是不適合用來學習。只適合用作在學習完國外的教材或者課程之後當作手冊來查詢。 3 對見過這些演算法又不太了解理論的童鞋比較好,對初學者來說解釋的不夠,對高手來說就是複習總結了一遍。 4 比較精簡的一本書,感覺是對章節末的論文的重點的完整的整理。掃盲了,接下來看看中文版的「The Elements of Statistical Learning」。 5 唉 。。。。。。 95 第84頁(6.21)下面L(P,w)對P(y|x)求偏導求錯了,@李航博士 96 對加深對經典模型的理解有幫助 97 偏理論,但不費解,功底很好 98 svm推導詳細。不過公式的符號表達方面的系統性不如Ng的講義完整。 99 前MSRA大牛的作品,適合入門用。 100 寫的清晰易懂

6.最後算出前100條評論的平均得分是

the average score of this book is 43.73626373626374

Tags: