zoukankan      html  css  js  c++  java
  • Python爬取网络数据——豆瓣评论

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

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

    检查网站约束
    ——

    在爬取数据之前有一点是一定要注意的,并不是所有的网站都允许我们去随意的爬取数据,因为这可能设计一些安全等问题。

    那么如何看你想爬取数据的网站的权限的呢? ——通过robots.txt文件

    以豆瓣为例,我们访问其域名下的/robots文件,如图:

    我们来分析一下robots.txt文件

    User-agent: * //允许所有代理爬取此站信息
    Disallow: /subject_search ///subject_search是禁止的链接,下同
    Disallow: /amazon_search
    Disallow: /search
    Disallow: /group/search
    Disallow: /event/search
    Disallow: /celebrities/search
    Disallow: /location/drama/search
    Disallow: /forum/
    Disallow: /new_subject
    Disallow: /service/iframe
    Disallow: /j/
    Disallow: /link2/
    Disallow: /recommend/
    Disallow: /doubanapp/card
    Disallow: /update/topic/
    Allow: /ads.txt
    Sitemap: https://www.douban.com/sitemap_index.xml
    Sitemap: https://www.douban.com/sitemap_updated_index.xml
    # Crawl-delay: 5 //在两次下载请求之间有5秒的时延

    如果你要爬取的数据是被允许的,下面就可以开始动起来了O(∩_∩)O

     

    数据获取
    ——

    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)

     运行结果:

  • 相关阅读:
    天眼查接口的调用
    EditPlus5.0注册码
    图片转化成base64字符串
    java根据图片的url地址下载图片到本地
    将字符串中的数字转化为文字
    String类型转json 转JSONObject 转 JSONArray 以及 遍历
    三个日期类型比较大小 20181123
    字符与字节的区别
    面向对象五大原则
    Struts/Servlet,action转到jsp后,CSS失效,路径问题(struts2,jsp路径,action路径,action跳转,相对路径,绝对路径)
  • 原文地址:https://www.cnblogs.com/Irvingcode/p/12427246.html
Copyright © 2011-2022 走看看