爬虫(三)bs4库

0.Beautiful Soup库的安装

在cmd以管理员身份输入:

pip install beautifulsoup4

BS库的安装小测  演示HTML页面地址 http://python123.io/ws/demo.html

获得该链接的源代码:

(1)右键点击 查看源代码

(2)IDLE输入:(对demo进行html的解析)

>>> import requests
>>> r=requests.get("http://python123.io/ws/demo.html")
>>> r.text
'<html><head><title>This is a python demo page</title></head>\r\n<body>\r\n<p class="title"><b>The demo python introduces several python courses.</b></p>\r\n<p class="course">Python is a wonderful general-purpose programming language. You can learn Python from novice to professional by tracking the following courses:\r\n<a href="http://www.icourse163.org/course/BIT-268001" class="py1" id="link1">Basic Python</a> and <a href="http://www.icourse163.org/course/BIT-1001870001" class="py2" id="link2">Advanced Python</a>.</p>\r\n</body></html>'
>>> demo=r.text
>>> from bs4 import BeautifulSoup
>>> soup=BeautifulSoup(demo,"html.parser")
>>> print(soup.prettify())

结果输出其网页源代码:

<html>
 <head>
  <title>
   This is a python demo page
  </title>
 </head>
 <body>
  <p class="title">
   <b>
    The demo python introduces several python courses.
   </b>
  </p>
  <p class="course">
   Python is a wonderful general-purpose programming language. You can learn Python from novice to professional by tracking the following courses:
   <a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">
    Basic Python
   </a>
   and
   <a class="py2" href="http://www.icourse163.org/course/BIT-1001870001" id="link2">
    Advanced Python
   </a>
   .
  </p>
 </body>
</html>

1.Beautiful Soup库的基本元素

Beautiful Soup库是解析、遍历、维护“标签树”的功能库。

from bs4 import BeautifulSoup
soup=BeautifulSoup("<html>data</html>","html.parser")
soup2=BeautifulSoup(open("D://demo.html"),"html.parser")

BeautifulSoup对应一个HTML/XML文档的全部内容。

BS类的基本元素 <p class="title">...</p>

Tag标签

说明:Tag是最基本的信息组织单元,分别用<>和</>表明开头和结尾。

>>> import requests
>>> r=requests.get("http://python123.io/ws/demo.html")
>>> demo=r.text
>>> from bs4 import BeautifulSoup
>>> soup = BeautifulSoup(demo,"html.parser")
>>> soup.title
<title>This is a python demo page</title>
>>> tag=soup.a
>>> tag
<a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">Basic Python</a>
>>> type(tag)
<class 'bs4.element.Tag'>

任何存在于HTML语法中的标签都可以用soup.<tag>访问获得当HTML文档中存在多个相同<tag>对应内容时,soup.<tag>返回第一个。

Tag的name(名字)

说明:标签的名字,<p>...</p>的名字是'p',格式:<tag>.name

<tag>对象的名字:通过<tag>.name获取,字符串类型

>>> soup.a.name
'a'
>>> soup.a.parent.name
'p'
>>> soup.a.parent.parent.name

Tag的attrs(属性)

说明:标签的属性,字典形式组织,格式:<tag>.attrs

每个<tag>对象可以有0或多个属性:通过<tag>.attrs获取,字典类型

>>> tag=soup.a
>>> tag.attrs
{'href': 'http://www.icourse163.org/course/BIT-268001', 'class': ['py1'], 'id': 'link1'}
>>> tag.attrs['class']
['py1']
>>> tag.attrs['href']
'http://www.icourse163.org/course/BIT-268001'
>>> type(tag.attrs)
<class 'dict'>

Tag的NavigableString

说明:标签内非属性字符串,<>...</>中字符串,格式:<tag>.string

<tag>对象内包含的字符串:通过<tag>.string获取,NavigableString类型,可以跨越多个层次。

>>> soup.a
<a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">Basic Python</a>
>>> soup.a.string
'Basic Python'
>>> soup.p
<p class="title"><b>The demo python introduces several python courses.</b></p>
>>> soup.p.string
'The demo python introduces several python courses.'
>>> type(soup.p.string)
<class 'bs4.element.NavigableString'>

Tag的Comment

说明:标签内字符串的注释部分,一种特殊的Comment类型

Comment是一种特殊的文字类型。

>>> newsoup=BeautifulSoup("<b><!--This is a comment--></b><p>This is not a comment</p>","html.parser")
>>> newsoup.b.string
'This is a comment'
>>> type(newsoup.b.string)
<class 'bs4.element.Comment'>
>>> newsoup.p.string
'This is not a comment'
>>> type(newsoup.p.string)
<class 'bs4.element.NavigableString'>

2.基于bs4库的HTML内容遍历方法

A.标签树的下行遍历

标签树的下行遍历代码举例:

from bs4 import BeautifulSoup
new_soup=BeautifulSoup("<div><p>A</p>B<p>C</p></div>","html.parser")
print("儿子结点:")
for i,child in enumerate(new_soup.div.children):
    print(i+1,child)
print("子孙结点:")
for i,child in enumerate(new_soup.div.descendants):
    print(i+1,child)

结果输出:

儿子结点:
1 <p>A</p>
2 B
3 <p>C</p>
子孙结点:
1 <p>A</p>
2 A
3 B
4 <p>C</p>
5 C

BeautifulSoup类型是标签树的根结点。

>>> soup=BeautifulSoup(demo,"html.parser")
>>> soup.head
<head><title>This is a python demo page</title></head>
>>> soup.head.contents
[<title>This is a python demo page</title>]
>>> soup.body.contents
['\n', <p class="title"><b>The demo python introduces several python courses.</b></p>, '\n', <p class="course">Python is a wonderful general-purpose programming language. You can learn Python from novice to professional by tracking the following courses:

<a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">Basic Python</a> and <a class="py2" href="http://www.icourse163.org/course/BIT-1001870001" id="link2">Advanced Python</a>.</p>, '\n']
>>> len(soup.body.contents)
5
>>> soup.body.contents[1]
<p class="title"><b>The demo python introduces several python courses.</b></p>

B.标签树的上行遍历

1

遍历所有先辈结点,包括soup本身,所以要区别判断。

C.标签树的平行遍历

>>> from bs4 import BeautifulSoup
>>> soup=BeautifulSoup(demo,"html.parser")
>>> soup.a.next_sibling
' and '
>>> soup.a.next_sibling.next_sibling
<a class="py2" href="http://www.icourse163.org/course/BIT-1001870001" id="link2">Advanced Python</a>
>>> soup.a.previous_sibling
'Python is a wonderful general-purpose programming language. You can learn Python from novice to professional by tracking the following courses:\r\n'
>>> soup.a.previous_sibling.previous_sibling
>>> soup.a.parent
<p class="course">Python is a wonderful general-purpose programming language. You can learn Python from novice to professional by tracking the following courses:

<a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">Basic Python</a> and <a class="py2" href="http://www.icourse163.org/course/BIT-1001870001" id="link2">Advanced Python</a>.</p>

注意:

平行遍历(all):

3.基于bs4库的HTML格式化和编码

bs4库的prettify()方法

方法:<tag>.prettify()

使HTML内容更加“友好”的显示,为HTML标签及其内容添加'\n',标签对象和soup对象均可调用此方法。

>>> from bs4 import BeautifulSoup
>>> soup=BeautifulSoup(demo,"html.parser")
>>> soup.prettify()
'<html>\n <head>\n  <title>\n   This is a python demo page\n  </title>\n </head>\n <body>\n  <p class="title">\n   <b>\n    The demo python introduces several python courses.\n   </b>\n  </p>\n  <p class="course">\n   Python is a wonderful general-purpose programming language. You can learn Python from novice to professional by tracking the following courses:\n   <a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">\n    Basic Python\n   </a>\n   and\n   <a class="py2" href="http://www.icourse163.org/course/BIT-1001870001" id="link2">\n    Advanced Python\n   </a>\n   .\n  </p>\n </body>\n</html>'
>>> print(soup.prettify())
<html>
 <head>
  <title>
   This is a python demo page
  </title>
 </head>
 <body>
  <p class="title">
   <b>
    The demo python introduces several python courses.
   </b>
  </p>
  <p class="course">
   Python is a wonderful general-purpose programming language. You can learn Python from novice to professional by tracking the following courses:
   <a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">
    Basic Python
   </a>
   and
   <a class="py2" href="http://www.icourse163.org/course/BIT-1001870001" id="link2">
    Advanced Python
   </a>
   .
  </p>
 </body>
</html>

由上面可以看出print可以打印出\n换行。

bs4库将任何HTML输入都变成utf-8编码(国际通用的编码格式)。

Pyhton 3.x默认支持编码是utf-8,解析无障碍。

>>> soup=BeautifulSoup("<p>中文</p>","html.parser")
>>> soup.p.string
'中文'
>>> print(soup.p.prettify())
<p>
中文
</p>

4.单元小结

发布了219 篇原创文章 · 获赞 13 · 访问量 9804

猜你喜欢

转载自blog.csdn.net/qq_35812205/article/details/104257099
今日推荐