抓取《统计学习方法》前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