网页解析方法-BeautifulSoup简明使用指南

摘要:获得网页的html文档后,需要先解析html文档,才能提取所需文本。BeautifulSoup是笔者认为最好用的网页解析工具。

00 安装bs库

pip install bs4

01 解析html

网页解析方法-BeautifulSoup简明使用指南的图1

import requests
import chardet
from bs4 import BeautifulSoup
headers={'User-Agent':'Mozillaxxxxxxxxxx'}
link='https://xxxxxxxxxxxxxx'
res=requests.get(link,headers=headers,timeout=10)
res.encoding=chardet.detect(res.content)['encoding']
soup=BeautifulSoup(res.text,'lxml') #使用BeautifulSoup解析res

查看一下soup;

print(soup)

网页解析方法-BeautifulSoup简明使用指南的图2

很像我们在浏览器上查看的html,有时候为了更好的排版,一般都使用;

print(soup.prettify())

网页解析方法-BeautifulSoup简明使用指南的图3

其实BeautifulSoup的作用就是将html文档转化了一下(转化成树结构),并且在这个树结构中,分为四种对象:Tag,NavigableString,Comment,BeautifulSoup。Tag对象就是原html的标记;NavigableString对象就是原html的文本;Comment对象特殊类型的NavigableString对象;BeautifulSoup对象就是文档的全部内容。其中最重要的两个对象是Tag和NavigableString。

02 元素定位(遍历)

仅仅tag进行遍历,只定位第一个元素;

soup.body.a

定位所有的子节点元素;

soup.body.contents
soup.body.children

可以加编号,定位某个;soup.body.children[2]

定位所有子孙节点(包括子节点的子节点);

soup.body.descendants

定位父节点元素;soup.body.parent

定位父辈节点;soup.body.parents

定位兄弟节点:next_sibling,previous_sibling,next_siblings,previous_siblings;

定位元素内容:next_element,next_elements,previous_element,previous_elements

03 元素定位(搜索)

本文介绍soup.find_all()的使用方法,其它读者可以举一反三。

使用tag定位;soup.find_all('b')

tag里使用正则;soup.find_all(re.compile("^b"))

tag里使用列表,同时定位多个;soup.find_all(["a", "b"])

tag里使用True;soup.find_all(True)

使用属性定位;soup.find_all(id='link2');soup.find_all(attrs={"data-foo": "value"})

属性里使用正则;soup.find_all(href=re.compile("elsie"))

属性里使用True;soup.find_all(class_=True)

同时满足多个属性;soup.find_all(href=re.compile("elsie"), id='link1')

tag和属性一起使用;soup.find_all("a", class_="sister")

使用内容定位;soup.find_all(string="Elsie")

内容里使用正则;soup.find_all(string=re.compile("Dormouse"))

内容里使用列表;soup.find_all(string=["Tillie", "Elsie", "Lacie"])

使用limit,限制搜索个数;soup.find_all("a", limit=2)

使用recursive=False,只搜索直接子节点;soup.html.find_all("title", recursive=False)

soup.find()和find_all()的区别,find()只搜索第一个。

04 元素定位(CSS选择器)

使用tag;soup.select("body");soup.select("p > a")

指定序号;soup.select("p > a:nth-of-type(2)")

使用#id;soup.select("#link1")

使用.class;soup.select(".sister")

同时定位多个;soup.select("#link1,#link2")

联合使用;soup.select("p > #link1");soup.select("a#link2");soup.select('a[href]');

soup.select('a[href^="http://example.com/"]')
soup.select('a[href*=".com/"]')
soup.select('a[href$="tillie"]')

只定位第一个;soup.select_one(".sister")

(1条)
默认 最新
牛逼啊山哥
评论 点赞 1
点赞 2 评论 1 收藏
关注