爬虫网页分析--beautifulsoup4

版权声明:随意了,开心就好。反正是给大家分享的笔记 https://blog.csdn.net/u011486491/article/details/84262724

爬虫网页分析--beautifulsoup4

我们用到的html示例:
​
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>
"""

四大对象种类

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

  • Tag

  • NavigableString

  • BeautifulSoup

  • Comment

Tag

Tag 通俗点讲就是 HTML 中的一个个标签,例如:

print soup.title
# <title>The Dormouse's story</title>
​
print soup.head
# <head><title>The Dormouse's story</title></head>
​
print soup.a
# <a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>
​
print soup.p
# <p class="title" name="dromouse"><b>The Dormouse's story</b></p>
​
print type(soup.p)
# <class 'bs4.element.Tag'>

对于tag来说,它有两个重要的属性,是 name 和 attrs

print soup.name
# [document] #soup 对象本身比较特殊,它的 name 即为 [document]
​
print soup.head.name
# head #对于其他内部标签,输出的值便为标签本身的名称
​
print soup.p.attrs
# {'class': ['title'], 'name': 'dromouse'}
# 在这里,我们把 p 标签的所有属性打印输出了出来,得到的类型是一个字典。
​
print soup.p['class'] # soup.p.get('class')
# ['title'] #还可以利用get方法,传入属性的名称,二者是等价的
​
soup.p['class'] = "newClass"
print soup.p # 可以对这些属性和内容等等进行修改
# <p class="newClass" name="dromouse"><b>The Dormouse's story</b></p>
​
del soup.p['class'] # 还可以对这个属性进行删除
print soup.p
# <p name="dromouse"><b>The Dormouse's story</b></p>

NavigableString

获取标签内部的文字

print soup.p.string
# The Dormouse's story
​
print type(soup.p.string)
# In [13]: <class 'bs4.element.NavigableString'>

BeautifulSoup

它表示的是一个文档的内容,可以把它当作 Tag 对象,是一个特殊的 Tag,我们可以分别获取它的类型,名称。

print type(soup.name)
# <type 'unicode'>
​
print soup.name 
# [document]
​
print soup.attrs # 文档本身的属性为空
# {}

Comment

它是一个特殊类型的 NavigableString 对象,其输出的内容不包括注释符号

print soup.a
# <a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>
​
print soup.a.string
# Elsie 
​
print type(soup.a.string)
# <class 'bs4.element.Comment'>

beautifilsoup4的使用:

遍历节点

直接子节点 :

.contents .children属性

.content

属性可以将tag的子节点列表的方式输出

print soup.head.contents 
#[<title>The Dormouse's story</title>]

.children

返回的不是一个 list,而是一个 list 生成器对象

rint soup.head.children
#<listiterator object at 0x7f71457f5710>
​
for child in  soup.body.children:
    print child
   
# 打印结果
<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 class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>,
<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a> and
<a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>;

所有子节点:

.descendants

.contents 和 .children 属性仅包含tag的直接子节点,.descendants 属性可以对所有tag的子孙节点进行递归循环

for child in soup.descendants:
    print child

节点内容

.string

如果tag只有一个 NavigableString 类型子节点,那么这个tag可以使用 .string 得到子节点。

所搜文档树

find_all(name, attrs, recursive, text, **kwargs)

一般用法:
soup.find('p', attrs={'class':'first'}).text

name :参数查找所有名字为 name 的tag,字符串对象会被自动忽略掉

  • 字符串:查找与字符串完整匹配的内容

  • soup.find_all('b')
    # [<b>The Dormouse's story</b>]
    ​
    print soup.find_all('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>]
  • 传正则表达式:通过正则表达式的 match() 来匹配内容.

    for tag in soup.find_all(re.compile("^b")):
        print(tag.name)
  • 传列表:找到文档中所有<a>标签和<b>标签

    soup.find_all(["a", "b"])
    # [<b>The Dormouse's story</b>,
    #  <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>]

keywords:用于筛选tag的属性()可以向上面那样传递一个字符串,来匹配属性的值。你也可以传递一个正则表达式,一个列表(list)。

soup.find_all(id='link2')
# [<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>]

attrs:匹配那些名字为Python保留字的属性, 例如class, for, 以及import; 或者那些不是keyword参数但是名字为Beautiful Soup搜索方法使用的参数名的属性, 例如name, recursive, limit, text, 以及attrs本身。

xmlSoup.findAll(attrs={"name" : "Alice"})
# [parent rel="mother" name="Alice"></parent>]
  • 组合使用

查找a标签中class为sister的标签

soup.find_all('a',class_='sister')

CSS选择器

它与 find_all 方法有异曲同工之妙的查找方法

注意:写 CSS 时,标签名不加任何修饰,类名前加.id名前加#

通过标签名查找

print soup.select('title') 
#[<title>The Dormouse's story</title>]
​
print soup.select('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>]
​
print soup.select('b')
#[<b>The Dormouse's story</b>]

通过类名查找

print soup.select('.sister')
#[<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>]

通过 id 名查找

print soup.select('#link1')
#[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>]

组合查找

组合查找即和写 class 文件时,标签名与类名、id名进行的组合原理是一样的,例如查找 p 标签中,id 等于 link1的内容,二者需要用空格分开

print soup.select('p #link1')
#[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>]

直接子标签查找,则使用 > 分隔

print soup.select("head > title")
#[<title>The Dormouse's story</title>]

属性查找

查找时还可以加入属性元素,属性需要用中括号括起来,注意属性和标签属于同一节点,所以中间不能加空格,否则会无法匹配到。

print soup.select('a[class="sister"]')
#[<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>]
​
print soup.select('a[href="http://example.com/elsie"]')
#[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>]

同样,属性仍然可以与上述查找方式组合,不在同一节点的空格隔开,同一节点的不加空格

print soup.select('p a[href="http://example.com/elsie"]')
#[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>]

获取内容

以上的 select 方法返回的结果都是列表形式,可以遍历形式输出,然后用 get_text() 方法来获取它的内容。

soup = BeautifulSoup(html, 'lxml')
print type(soup.select('title'))
print soup.select('title')[0].get_text()
​
for title in soup.select('title'):
    print title.get_text()

猜你喜欢

转载自blog.csdn.net/u011486491/article/details/84262724