当前位置 博文首页 > Python安装Bs4及使用方法

    Python安装Bs4及使用方法

    作者:Bibabu135766 时间:2021-06-18 17:44

    安装方法一:

    ①进入python文件夹执行指令(前提是支持pip指令):

    pip3 install Beautifulsoup4 

    ②回车待安装完成,如果出现以下红框中内容,即代表安装成功

    ③验证是否可以运行成功,运行cmd执行,引用模块import bs4回车未报错,则证明安装完成,可以正常使用了:

    安装方法二

    (像我们公司这种各种网络限制,使用pip就会出现无法安装,一直循环在retry):

    ①进入官网下载压缩包:Beautiful Soup官网下载链接

    ②将压缩包解压至python文件中,进入解压文件后输入指令(前面的python不可缺少):

    python setup.py install

    ③待运行完成后输入python,再输入help('modules')可以查看你当前python拥有的所有模块,如下:

    ④如上安装完成,同样检查是否可以正常引入bs4,输入:import bs4 回车

    安装方法三

    (如果是python3伙伴会发现,上面两种方法还是不行,运行help('modules')也找不到bs4模块,此时就需要使用以下方法了):

    ①同样进行上面第二种方法后,将BeautifulSoup4文件夹中的bs4文件夹拷贝到python安装目录下的lib中

    ②将python安装目录下的Tools/scripts/2to3.py文件也剪切到python安装目录下的lib中

    ③cmd中cd到lib目录,然后运行python 2to3.py bs4 -w即可

    基本用法:

    import bs4
    from bs4 import 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" rel="external nofollow"  class="sister" >Elsie</a>,
    <a href="http://example.com/lacie" rel="external nofollow"  class="sister" >Lacie</a> and
    <a href="http://example.com/tillie" rel="external nofollow"  class="sister" >Tillie</a>;
    and they lived at the bottom of a well.</p>
    
    <p class="story">...</p>
    """

    创建一个BeautifulSoup 对象

    soup = BeautifulSoup(html_doc,“html.parser”)

    格式化文档输出

    soup.prettify()

    在这里插入图片描述

    获取标题

    soup.title.text

    在这里插入图片描述

    获取所有标签属性

    soup.a.attrs

    在这里插入图片描述

    判断是否含有某个标签属性

    soup.a.has_attr(‘class')

    在这里插入图片描述

    获取标签的子元素

    list(soup.p.children)
    

    在这里插入图片描述

    list(soup.p.children)[0].text
    

    在这里插入图片描述

    取出所有标签

    soup.find_all(‘a')
    for a in soup.find_all(‘a'):
    print(a.attrs[‘href'])
    

    在这里插入图片描述

    找寻指定id

    soup.find(id=‘link3')
    

    在这里插入图片描述

    找出所有文字内容

    soup.get_text()

    在这里插入图片描述

    到此这篇关于Python安装Bs4及使用方法的文章就介绍到这了,更多相关Python安装Bs4使用内容请搜索站长博客以前的文章或继续浏览下面的相关文章希望大家以后多多支持站长博客!

    js