BeautifulSoup使用总结

    BeautifulSoup是Python的一个第三方库,可用于帮助解析html/XML等内容,以抓取特定的网页信息。目前最新的是v4版本,这里主要总结一下我使用的v3版本解析html的一些常用方法。
1.初始化
   导入模块
  1. #!/usr/bin/env python
  2. from BeautifulSoup import BeautifulSoup       #process html
  3. #from BeautifulSoup import BeautifulStoneSoup #process xml
  4. #import BeautifulSoup                         #all
    创建对象:str初始化,常用urllib2或browser返回的html初始化BeautifulSoup对象。
  1. doc = ['<html><head>hello<title>PythonClub.org</title></head>',
  2.        '<body><p id="firstpara" align="center">This is paragraph <b>one</b> of ptyhonclub.org.',
  3.        '<p id="secondpara" align="blah">This is paragraph <b>two</b> of pythonclub.org.',
  4.        '</html>']
  5. soup = BeautifulSoup(''.join(doc))
    指定编码:当html为其他类型编码(非utf-8和asc ii),比如GB2312的话,则需要指定相应的字符编码,BeautifulSoup才能正确解析。
  1. htmlCharset = "GB2312"
  2. soup = BeautifulSoup(respHtml, fromEncoding=htmlCharset)

2.获取tag内容
   寻找感兴趣的tag块内容,返回对应tag块的剖析树
  1. head = soup.find('head')
  2. #head = soup.head
  3. #head = soup.contents[0].contents[0]
  4. print head
    返回内容:<head>hello<title>PythonClub.org</title></head>
   说明一下,contents属性是一个列表,里面保存了该剖析树的直接儿子。
  1. html = soup.contents[0]       # <html> ... </html>
  2. head = html.contents[0]       # <head> ... </head>
  3. body = html.contents[1]       # <body> ... </body>

3.获取关系节点
    使用parent获取父节点
  1. body = soup.body
  2. html = body.parent             # html是body的父亲
     使用 nextSibling, previousSibling获取前后兄弟
  1. head = body.previousSibling    # head和body在同一层,是body的前一个兄弟
  2. p1 = body.contents[0]          # p1, p2都是body的儿子,我们用contents[0]取得p1
  3. p2 = p1.nextSibling            # p2与p1在同一层,是p1的后一个兄弟, 当然body.content[1]也可得到
    contents[]的灵活运用也可以寻找关系节点, 寻找祖先或者子孙可以采用findParent(s), findNextSibling (s), findPreviousSibling (s)

4.find/findAll用法详解
   函数原型:find(name=None, attrs={}, recursive=True, text=None, **kwargs),findAll会返回所有符合要求的结果,并以list返回。
    tag搜索
  1. find(tagname)                                  # 直接搜索名为tagname的tag 如:find('head')
  2. find(list)                                     # 搜索在list中的tag,如: find(['head', 'body'])
  3. find(dict)                                     # 搜索在dict中的tag,如:find({'head':True, 'body':True})
  4. find(re.compile(''))                           # 搜索符合正则的tag, 如:find(re.compile('^p')) 搜索以p开头的tag
  5. find(lambda)                       # 搜索函数返回结果为true的tag, 如:find(lambda name: if len(name) == 1) 搜索长度为1的tag
  6. find(True)                                     # 搜索所有tag

    attrs搜索
  1. find(id='xxx')                                  # 寻找id属性为xxx的
  2. find(attrs={id=re.compile('xxx'), algin='xxx'}) # 寻找id属性符合正则且algin属性为xxx的
  3. find(attrs={id=True, algin=None})               # 寻找有id属性但是没有algin属性的

  1. resp1 = soup.findAll('a', attrs = {'href': match1})
  2. resp2 = soup.findAll('h1', attrs = {'class': match2})
  3. resp3 = soup.findAll('img', attrs = {'id': match3})

    text搜索
   文字的搜索会导致其他搜索给的值如:tag, attrs都失效。方法与搜索tag一致
  1. print p1.text
  2. # u'This is paragraphone.'
  3. print p2.text
  4. # u'This is paragraphtwo.'
  5. # 注意:1,每个tag的text包括了它以及它子孙的text。2,所有text已经被自动转为unicode,如果需要,可以自行转码encode(xxx)


   recursive和limit属性
    recursive=False表示只搜索直接儿子,否则搜索整个子树,默认为True。当使用findAll或者类似返回list的方法时,limit属性用于限制返回的数量,如findAll('p', limit=2): 返回首先找到的两个tag

 

 

在前面的例子用,我用了BeautifulSoup来从58同城抓取了手机维修的店铺信息,这个库使用起来的确是很方便的。本文是BeautifulSoup 的一个详细的介绍,算是入门把。文档地址:http://www.crummy.com/software/BeautifulSoup/bs4/doc/

什么是BeautifulSoup?

Beautiful Soup 是用Python写的一个HTML/XML的解析器,它可以很好的处理不规范标记并生成剖析树(parse tree)。 它提供简单又常用的导航(navigating),搜索以及修改剖析树的操作。它可以大大节省你的编程时间。

直接看例子:

#!/usr/bin/python
# -*- coding: utf-8 -*-

from bs4 import BeautifulSoup

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

"""

soup = BeautifulSoup(html_doc)

print soup.title

print soup.title.name

print soup.title.string

print soup.p

print soup.a

print soup.find_all('a')

print soup.find(id='link3')

print soup.get_text()

结果为:

<title>The Dormouse's story</title>
title
The Dormouse's story
<p class="title"><b>The Dormouse's story</b></p>
<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>
[<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>, <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>, <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
<a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>

The Dormouse's story
The Dormouse's story
Once upon a time there were three little sisters; and their names were
Elsie,
Lacie and
Tillie;
and they lived at the bottom of a well.
...

可以看出:soup 就是BeautifulSoup处理格式化后的字符串,soup.title 得到的是title标签,soup.p  得到的是文档中的第一个p标签,要想得到所有标签,得用find_all

函数。find_all 函数返回的是一个序列,可以对它进行循环,依次得到想到的东西.

get_text() 是返回文本,这个对每一个BeautifulSoup处理后的对象得到的标签都是生效的。你可以试试 print soup.p.get_text()

其实是可以获得标签的其他属性的,比如我要获得a标签的href属性的值,可以使用 print soup.a['href'],类似的其他属性,比如class也是可以这么得到的(soup.a['class'])。

特别的,一些特殊的标签,比如head标签,是可以通过soup.head 得到,其实前面也已经说了。

如何获得标签的内容数组?使用contents 属性就可以 比如使用 print soup.head.contents,就获得了head下的所有子孩子,以列表的形式返回结果,

可以使用 [num]  的形式获得 ,获得标签,使用.name 就可以。

获取标签的孩子,也可以使用children,但是不能print soup.head.children 没有返回列表,返回的是 <listiterator object at 0x108e6d150>,

不过使用list可以将其转化为列表。当然可以使用for 语句遍历里面的孩子。

关于string属性,如果超过一个标签的话,那么就会返回None,否则就返回具体的字符串print soup.title.string 就返回了 The Dormouse's story

超过一个标签的话,可以试用strings

向上查找可以用parent函数,如果查找所有的,那么可以使用parents函数

查找下一个兄弟使用next_sibling,查找上一个兄弟节点使用previous_sibling,如果是查找所有的,那么在对应的函数后面加s就可以

如何遍历树?

 使用find_all 函数

find_all(nameattrsrecursivetextlimit**kwargs)

举例说明:

print soup.find_all('title')
print soup.find_all('p','title')
print soup.find_all('a')
print soup.find_all(id="link2")
print soup.find_all(id=True)

返回值为:

[<title>The Dormouse's story</title>]
[<p class="title"><b>The Dormouse's story</b></p>]
[<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>, <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>, <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
[<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>]
[<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>, <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>, <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]

通过css查找,直接上例子把:

print soup.find_all("a", class_="sister")
print soup.select("p.title")

通过属性进行查找
print soup.find_all("a", attrs={"class": "sister"})

通过文本进行查找
print soup.find_all(text="Elsie")
print soup.find_all(text=["Tillie", "Elsie", "Lacie"])

限制结果个数
print soup.find_all("a", limit=2)

结果为:

[<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>, <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>, <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
[<p class="title"><b>The Dormouse's story</b></p>]
[<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>, <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>, <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]
[u'Elsie']
[u'Elsie', u'Lacie', u'Tillie']
[<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>, <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>]

总之,通过这些函数可以查找到想要的东西。

---end---

 

 

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python BeautifulSoup是一个用于解析HTML和XML文件的Python库。它能够将复杂的HTML和XML文档转换成易于遍历、搜索和修改的Python对象树。通过使用BeautifulSoup,我们可以方便地提取出网页中的各种标签和内容,进行数据分析和处理。BeautifulSoup有两个常用版本:BeautifulSoup 3和BeautifulSoup 4(简称BS4)。目前,更多的是使用BeautifulSoup 4,也就是BS4版本。如果你在使用BeautifulSoup时遇到了问题,比如报错“‘NoneType’ object is not callable using ‘find_all’ in BeautifulSoup”,可能是因为你需要安装BeautifulSoup4版本或bs4。 要使用BeautifulSoup,你需要安装BeautifulSoup4库。如果你使用的是Anaconda等集成开发环境,它的BeautifulSoup扩展包通常已经预装了,可以直接使用。一旦安装好了BeautifulSoup,你就可以使用它的各种方法来解析网页,提取标签信息和内容。例如,你可以使用BeautifulSoup的find方法来查找指定的标签,使用get_text方法来获取标签的文本内容,使用find_all方法来查找所有符合条件的标签等等。 总结起来,Python BeautifulSoup是一个功能强大的库,可以帮助我们解析和处理HTML和XML文件。它提供了很多方便的方法和技巧,使得我们能够轻松地提取出网页中的各种信息,并进行进一步的数据处理和分析。<span class="em">1</span><span class="em">2</span><span class="em">3</span><span class="em">4</span>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值