Python Beautiful Soup笔记

安装解析器

$ apt-get install Python-lxml
$ easy_install lxml
$ pip install lxml

导入 Beautiful Soup

from bs4 import BeautifulSoup

创建 BeautifulSoup对象

bsObj = BeautifulSoup('html', 'lxml') # lxml库
bsObj = BeautifulSoup(markup, "html.parser") # python标准库

(文档链接)https://www.crummy.com/software/BeautifulSoup/bs4/doc/index.html

格式化输出

print(bsObj.prettify())

从文档中找到所有链接

for link in soup.find_all('a'):
    print(link.get('href'))
    # http://example.com/elsie
    # http://example.com/lacie
    # http://example.com/tillie

Name

每个Tag都有一个名字,通过Tag.name即可获取标签的名字

for link in soup.find_all('a'):
    print(link.name)

$a
$a

父节点 parent / 所有父节点 .parents

title_tag = bsObj.title
title_tag.parent

兄弟节点

兄弟节点就是同一个标签下的所有直接子节点
.previous_sibling
.next_sibling
.previous_siblings 可迭代
.next_siblings 可迭代

对象种类

Beautiful Soup将复杂HTML文档转换成一个复杂的树形结构,每个节点都是Python对象,所有对象可以归纳为4种: Tag , NavigableString , BeautifulSoup , Comment .

Tag

Tag 对象与XML或HTML原生文档中的tag相同
如:html中的

等标签

posted @ 2017-11-11 21:50  小土坡  阅读(28)  评论(0)    收藏  举报