Python安装Bs4使用 Python安装Bs4及使用方法

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Python安装Bs4使用 Python安装Bs4及使用方法

Bibabu135766   2021-04-28 我要评论
想了解Python安装Bs4及使用方法的相关内容吗,Bibabu135766在本文为您仔细讲解Python安装Bs4使用的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:Python安装Bs4使用,Python安装Bs4,下面大家一起来学习吧。

安装方法一:

①进入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" id="link1">Elsie</a>,
<a href="http://example.com/lacie" rel="external nofollow"  class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" rel="external nofollow"  class="sister" id="link3">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()

在这里插入图片描述

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们