python网络爬虫与信息提取 答案_PYTHON网络爬虫与信息提取[BeautifulSoup](单元四)

1 简介

from bs4 import BeautifulSoup

soup=BeautifulSoup(

data

,'html.parser')

2 基本元素

解析,遍历,维护,标签树的库

...

   tag对

名称 (属性 attributes)

beautifulsoup 或bs4

from bs4 import BeautifulSoup

import bs4

beautifulSoup 雷

html--------标签树(字符串)转换为beautifulsoup类

from bs4 import BeautifulSoup

soup=

注:解析器(4种)

html.parser    安装bs4库

lxml      pip install lxml

xml                同上

html5lib    pipinstall html5lib

beautiful 类的基本元素

Tag  标签 尖括号开头结尾

Name  格式:.name  

的名字是 ''p''

Attributes      标签的属性,字典形式组织  .attrs

NavigableString 标签内非属性字符串  表示尖括号之间的内容

soup.a.string 就可以了

Comment     标签内字符串的注释部分

用string 也可以得出这个类型

3 标签树的遍历

.contents 获得子节点的列表

.children 获得子节点的迭代形式

.descendants 获得子孙的迭代形式

儿子节点不管包括标签 还包括\n

soup.body.contents

.parent 节点的父亲标签

.parnets 节点的先辈形式迭代版的

平行遍历(返回按照html文本顺序的节点标签)

平行遍历时实在同一个父标签下的遍历

.next_sibling

.previous_sibling

.next_siblings   迭代版

.next_previous_siblings 迭代版

4 基于bs4显示html的内容

from bs4 import BeautifulSoup

soup=BeautifulSoup(demo,"html.parser")   //加载解析器的语句

soup.prettify()  //soup 是 BeautifulSoup类型 用以解析html 或者遍历html

"prettify()方法非常好用"

#增加换行符

print(soup.prettify())

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值