Python爬取网络数据——豆瓣评论

豆瓣这个网站做网络爬虫的例子教学是极好的,我这个入门者今天也来分享下自己的第一个爬虫例程~ (●‘?‘●)

爬虫的过程由数据获取+数据解析来组成:

数据获取
——

1 选择数据获取工具

想要爬取有用的数据,首先要获得数据

抓取数据主要有以下几种方式:

1)urllib内建模块,尤其是urllib.request,可以方便的抓取网页内容。

2)Requests第三方库,逐渐取代了urllib.request,适合做中小型网络爬虫的开发。

3)Scrapy框架,适合做大型网络爬虫的开发。

本文选择Requests库来实现。

2  Requests库的使用

获取网络数据主要使用requests.get方法,实际上就是向网站的服务器发送HTTP协议的GET请求

r = requests.get(‘https://book.douban.com/subject/30218241/comments/‘)

get方法的参数很多,其中还有一个重要的参数是headers,用来表示发送的数据帧的头部信息,现在很多网站都有反爬机制,不加头部会返回418(正常返回200)。

具体头部的写法下面会讲(¬︿??¬☆)

3 Requests的其它使用方法

 

1)假设获取的是二进制文件,则可以借鉴如下方法保存数据:

import requests
 
r = requests.get(‘https://www.baidu.com/img/bd_logo1.png‘)
with open(‘baidu.png‘, ‘wb‘) as fp:
   fp.write(r.content)

2)有些网站会对http请求的Headers的User-Agent进行检测,需将headers信息传递给get函数的headers参数,例如豆瓣最近也有了此要求,例如知乎,直接访问会返回400,加上headers参数后可正确返回:

>>> re = requests.get(‘https://www.zhihu.com‘)
>>> re.status_code
400
# headers可从http测试网站https://httpbin.org或浏览器的“开发者工具”获得
>>> headers = {"User-Agent": "Mozilla/5.0 (X11; Linux i686) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.83 Safari/535.11"}
>>> re = requests.get(‘https://www.zhihu.com‘, headers = headers)
>>> re.status_code
200

数据解析
——

1 解析工具选择

a)BeautifulSoup库:很方便的从XML和HTML中提取数据

b)2 re正则表达式模块:更适合复杂的数据解析服务

因为本例程简单,所以就选择BeautifulSoup库,安装和导入方法:

pip安装: pip3 install bs4

导入:from bs4 import BeautifulSoup

2 选择BeautifulSoup的解析器

对于html文件最常用LXML解析器,速度比较快,文档容错能力强
安装lxm: pip3 install lxml

3 如何使用BeautifulSoup?

定义makeup为简单的html语句,使用BeautifulSoup方法来生成对象:

markup = ‘<p class="title"><b>The Little Prince</b></p>‘
soup = BeautifulSoup(markup, "lxml")#生成BeautifulSoup对象
任何html标签内容都可以用BeautifulSoup对象.Tag形式得到
print(soup.p)
得到:<p class="title"><b>The Little Prince</b></p>
print(soup.p.string)
得到:The Little Prince

使用BeautifulSoup对象.find_all(‘b‘)会以list的形式返回找到的所有b标签,(find_all还可以带上属性名)

print(soup.find_all(‘b‘))得到:[<b>The Little Prince</b>]

使用以上的功能组合就可以将获取的数据进行过滤,最终得到我们想要的数据。

完整代码及运行结果
——

import requests
import random
from bs4 import BeautifulSoup

headers = {"User-Agent": "Mozilla/5.0 (X11; Linux i686) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.83 Safari/535.11"}

r = requests.get(‘https://book.douban.com/subject/30218241/comments/‘,headers=headers)#不加头会检测到爬虫返回418
print(r.status_code)

soup = BeautifulSoup(r.text, "lxml")
pattern = soup.find_all(‘span‘,‘short‘)#找到评论所在行(标签:span,属性内容:short)

for item in pattern:
    print(item.string)

 运行结果:

Python爬取网络数据——豆瓣评论

相关推荐