Python爬虫:数据解析和提取——Beautiful Soup

 一.安装

pip3 install lxml
pip3 install beautifulsoup4

二.导入与实例化

导入

from bs4 import BeautifulSoup

实例化

  • 本地对象

fp=open(',/test.html','r',encoding='utf-8)
html=BeautifulSoup(fp,'lxml')
  • 网络对象(page_text为requests请求获得)
html=BeautifulSoup(page_text,'lxml')

三.Beautiful Soup规则

实例

html='''
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title" name="dromouse"><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>
'''

1. 选择节点

  1.1 获取节点

result=html.head
#运行结果
<head><title>The Dormouse's story</title></head>

  1.2 多个节点只获取第一个匹配的节点

result=html.p
#运行结果
<p class="title" name="dromouse"><b>The Dormouse's story</b></p>

  1.3 嵌套选择

result=html.head.title
#运行结果
<title>The Dormouse's story</title>

2. 提取信息

  2.1 获取节点名称

result=html.title.name
#运行结果
title

  2.2 获取节点属性

result=html.p['name']
#运行结果
dromouse

  2.3 获取节点内容

result=html.title.string
#运行结果
The Dormouse's story

实例

html='''
<html>
    <head>
        &l
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值