zoukankan      html  css  js  c++  java
  • python-爬虫 爬虫利器BeautifulSoup

    BeautifulSoup


    1.BeautifulSoup库介绍(了解)

    # BeautifulSoup库介绍:
    BeautifulSoup也是一个解析库  
    BS解析数据是依赖解析器的, BS支持的解析器有html.parser, lxml, xml, html5lib等, 其中lxml解析器解析速度快, 容错能力强.
    BS现阶段应用的解析器多数是lxml
    pip install bs4
    
    # bs4的编码流程:
    from bs4 import BeautifulSoup
    soup = BeautifulSoup(res.text, 'lxml')
    tag = soup.select('CSS选择器表达式')  # css选取器 (*****)
    tag = soup.nodename()  # 节点选择器(*)
    tag = soup.findall()  # 方法选择器(***)
    
    # xpath编码流程:
    from lxml import etree
    tree = etree.HTML(res.text)
    tag = tree.xpath()
    
    # 选择器介绍:
    1.节点选择器
    2.方法选择器
    3.CSS选择器(*****)
    

    2.BS4选择器使用(重点)

    # 1.节点选择器
    from bs4 import BeautifulSoup
    soup = BeautifulSoup(res.text, 'lxml')
    tag = soup.a   # 只取第一个a标签就停了
    
    # 2.方法选择器
    find_all(name, attrs, text, limit):
        1).soup.find_all(name='nodename'):根据节点名定位节点
        2).soup.find_all(attrs={'attribute_name': 'attribute_value'}):根据属性定位, 多属性时, 一个即可定位
        3).soup.find_all(text=re.compile(r'...')):根据节点文本定位, 返回文本
        4).soup.find_all(name='nodename', limit=2):只返回两个结果
    find(name, attrs, text, limit): 区别于find_all, find()返回的是一个对象结果, find_all()返回的是一个列表
    
    # CSS选择器:
    属性选择器:
        
    1.根据节点名定位标签: 标签选择器
    soup.select('title')
    2.根据节点的class属性定位标签: class选择器(classical: 经典)
    soup.select('.panel')
    3.根据id属性定位标签: id选择器
    soup.select('#item')
    4.嵌套选择:
    ul_list = soup.select('ul')  # 得到的依然是一个列表数据类型
    for ul in ul_list:
      print(ul.select('li'))
    5.层级选择器
    soup.select('div > ul > li')   # 单层级选择器
    soup.select('div li')  # 多层级选择器
    # 获取节点的文本或属性:
    tag_obj.string: 获取直接子文本-->如果节点内有与直系文本平行的节点, 该方法拿到的是None
    tag_obj.get_text(): 获取子孙节点的所有文本
    tag_obj['attribute']: 获取节点属性
    
    # 练习示例:
    html = '''
        <div class="panel">
            <div class="panel-heading">
                <h4>BeautifulSoup练习</h4>
            </div>
            <div id="divtag">
            	这是一个div的直接子文本
            	<p>这是一个段落</p>
            </div>
    		<a href="https://www.baidu.com">这是百度的跳转连接</a>
    		<img class="imgtag" src="https://www.balabala.com/kjdfkdjf.jpg">
            <div class="panel-body">
                <ul class="list" id="list-1">
                    <li class="element">第一个li标签</li>
                    <li class="element">第二个li标签</li>
                    <li class="element">第三个li标签</li>
                </ul>
                <ul class="list list-small">
                    <li class="element">one</li>
                    <li class="element">two</li>
                </ul>
                <li class="element">测试多层级选择器</li>
            </div>
        </div>
    '''
    from bs4 import BeautifulSoup
    
    soup = BeautifulSoup(html, 'lxml')
    # 1.根据节点名定位节点, 获取其文本
    h4 = soup.select('h4')   # 标签选择器
    print(h4[0].get_text())
    
    # 2.根据class属性定位节点
    panel = soup.select('.panel-heading')
    print(panel)
    
    # 3.根据id属性定位节点
    ul = soup.select('#list-1')
    print(ul)
    
    # 4.嵌套选择
    ul_list = soup.select('ul')
    for ul in ul_list:
        li = ul.select('li')
        print(li)
        
    # 5.单层级选择器与多层级选择器
    li_list_single = soup.select(".panel-body > ul > li")
    li_list_multi = soup.select(".panel-body li")
    

    1. 案例: requests结合BS4实现深度爬取三国演义整部小说

    # 作业: 爬取整部三国演义小说, 写入txt文件: 'http://www.shicimingju.com/book/sanguoyanyi.html'
    
    import requests
    from bs4 import BeautifulSoup
    
    url = 'http://www.shicimingju.com/book/sanguoyanyi.html'
    headers = {
        'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36'
    }
    res = requests.get(url=url, headers=headers)
    soup = BeautifulSoup(res.text, 'lxml')
    a_list = soup.select(".book-mulu ul li a")
    for item in a_list:
        name = item.string
        href = item["href"]
        # print(href)
        full_url = 'http://www.shicimingju.com' + href
        detail_page = requests.get(url=full_url, headers=headers).text
        soup_detail = BeautifulSoup(detail_page, 'lxml')
        div = soup_detail.select(".chapter_content")[0]
        print(type(div.get_text()))
        with open('%s.txt' % name, 'w', encoding="utf-8") as f:
            f.write(div.get_text())
    
    从小白到大神的蜕变~~
  • 相关阅读:
    2018年NGINX最新版高级视频教程
    PHP 高级工程面试题汇总
    2018年最全Go语言教程零基础入门到进阶实战视频
    Mac和window生成ssh和查看ssh key
    33款可用来抓数据的开源爬虫软件工具
    什么是CMS系统
    对于做需求分析时的一些心得
    WPF和Silverlight的关系
    My97日期控件 My97 DatePicker Ver 3.0 正式版(转)
    HTML教程HTML技巧层的高级应用
  • 原文地址:https://www.cnblogs.com/tjw-bk/p/13752020.html
Copyright © 2011-2022 走看看