• 网页解析器(BeautifulSoup)-- Python


    分享一下关于 Python的网页解析器(BeautifulSoup)

     

    BeautifulSoup解析器

    为了实现解析器,可以选择使用正则表达式、html.parser、BeautifulSoup、lxml等,所以BeautifulSoup是比较好的选择。
    其中,正则表达式基于模糊匹配,而另外三种则是基于DOM结构化解析。

    安装测试

    1、安装,在命令行下执行pip install beautifulsoup4
    2、测试

    import bs4
    print(bs4)

    使用说明


    基本用法

    1、创建BeautifulSoup对象

    import bs4
    from bs4 import BeautifulSoup
    
    # 根据html网页字符串创建BeautifulSoup对象
    html_doc = """
    <html><head><title>The Dormouse's story</title></head>
    <body>
    <p class="title"><b>The Dormouse's story</b></p>
    
    <p class="story">Once upon a time there were three little sisters; and their names were
    <a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
    <a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
    <a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
    and they lived at the bottom of a well.</p>
    
    <p class="story">...</p>
    """
    soup = BeautifulSoup(html_doc)
    print(soup.prettify())
     

    2、访问节点

    print(soup.title)
    print(soup.title.name)
    print(soup.title.string)
    print(soup.title.parent.name)
    
    print(soup.p)
    print(soup.p['class'])

    3、指定tag、class或id

    print(soup.find_all('a'))
    print(soup.find('a'))
    print(soup.find(class_='title'))
    print(soup.find(id="link3"))
    print(soup.find('p',class_='title'))
    

      

    4、从文档中找到所有<a>标签的链接

    for link in soup.find_all('a'):
        print(link.get('href'))
    

      


    出现了警告,根据提示,我们在创建BeautifulSoup对象时,指定解析器即可。

    soup = BeautifulSoup(html_doc,'html.parser')
    

      

    5、从文档中获取所有文字内容

    print(soup.get_text())
    

      

    6、正则匹配

    link_node = soup.find('a',href=re.compile(r"til"))
    print(link_node)
    

      



  • 相关阅读:
    PowerCat DNS 隧道通信
    各种反弹shell方法总结备忘
    Halo-个人独立博客系统
    内网渗透之域渗透
    使用 EW 作Socks5代理内网穿透
    PowerShell攻击:nishang
    贝叶斯网络
    Anaconda的CondaHTTPError问题
    完美解决win10系统无法安装.NET Framework问题
    敏捷开发中如何做质量管理?
  • 原文地址:https://www.cnblogs.com/Barrybl/p/12618068.html
Copyright © 2020-2023  润新知