BeautifulSoup的安装和基本使用方式

“BeautifulSoup是用Python写的一个HTML/XML的解析器,它可以很好的处理不规范标记并生成剖析树(parse tree)。 它提供简单又常用的导航(navigating),搜索以及修改剖析树的操作。它可以大大节省解析网页的编程时间。”——引用自《BeautifulSoup文档》


1、BeautifulSoup的安装


BeautifulSoup官方网址:http://www.crummy.com/software/BeautifulSoup/,目前的最新版本:beautifulsoup4-4.5.3。

Beautiful Soup 4 通过PyPi发布,所以如果你无法使用系统包管理安装,那么也可以通过 easy_install 或 pip 来安装.包的名字是 beautifulsoup4 ,这个包兼容Python2和Python3.
easy_install beautifulsoup4
或者:pip install beautifulsoup4

【如果你没有安装 easy_install 或 pip ,那你也可以 下载beautifulsoup4-4.5.3.tar ,然后通过setup.py来安装:Python setup.py install】


2、BeautifulSoup4的基本使用方式:

  • 先使用from bs4 import BeautifulSoup导入模块(注意:Python对大小写敏感,不要写成beautifulsoup)。
  • 搭配requests模块提取网页的数据。
  • 使用BeautifulSoup产生一个html实例。
  • 应用BeautifulSoup所提供的函数存取html实例的数据,这些函数主要是以html文档的标签为目标进行操作。
3、示例:
from bs4 import BeautifulSoup
import requests
url ='http://www.timeanddate.com/weather/'
html = requests.get(url).text
sp = BeautifulSoup(html,"html.parser")
print("Type:",type(sp))
links = sp.find_all('a')
print("------>",links[10])
print("******",links[10].contents)
print("======",links[10].get('href'))

4、执行结果:

Type: <class 'bs4.BeautifulSoup'>
------> <a href="/custom/site.html">My Units</a>
****** ['My Units']
====== /custom/site.html

Process finished with exit code 0


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值