Python爬虫-BeautifulSoup库

本文介绍BeautifulSoup的基本使用方法,包括解析器的选择、基本元素的操作、遍历方法的应用、内容查找技巧等,并通过实例演示如何利用这些知识进行网页内容的抓取。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、解析器

bs4的HTML解析器
soup = BeautifulSoup('<html>data</html>','html.parser')
lxml的HTML解析器
BeautifulSoup('<html>data</html>','lxml')
xml的HTML解析器
BeautifulSoup('<html>data</html>','xml')
html5lib的解析器
BeautifulSoup('<html>data</html>','html5lib')

二、基本元素
(1)Tag标签

>>> r = requests.get("http://python123.io/ws/demo.html")
>>> demo = r.text
>>> demo
u'<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>'
>>> 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>

(2)Tag的name

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

(3)Tag的attrs

>>> tag.attrs
{u'href': u'http://www.icourse163.org/course/BIT-268001', u'class': [u'py1'], u'id': u'link1'}
>>> type(tag)
<class 'bs4.element.Tag'>

(4)Tag的NavigableString

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

(5)Tag的Comment

>>> nsoup = BeautifulSoup("<b><!--Comment--></b><p>Not Comment</p>","html.parser")
>>> nsoup.b.string
u'Comment'
>>> type(nsoup.b.string)
<class 'bs4.element.Comment'>
>>> nsoup.p.string
u'Not Comment'
>>> type(nsoup.p.string)
<class 'bs4.element.NavigableString'>

三、遍历方法
(1)下行遍历

.contents 子节点列表
>>> 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
[u'\n', <p class="title"><b>The demo python introduces several python courses.</b></p>, u'\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 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>, u'\n']
>>> len(soup.body.contents)
5
>>> soup.body.contents[1]
<p class="title"><b>The demo python introduces several python courses.</b></p>
.children  子节点迭代类型,用于循环遍历儿子节点
>>> for child in soup.body.children:
...     print(child)
...


<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>
.descendants  子孙节点的迭代类型,包含所有子孙节点
>>> for child in soup.body.descendants:
...     print(child)
...


<p class="title"><b>The demo python introduces several python courses.</b></p>
<b>The demo python introduces several python courses.</b>
The demo python introduces several python courses.


<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>
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>
Basic Python
 and
<a class="py2" href="http://www.icourse163.org/course/BIT-1001870001" id="link2">Advanced Python</a>
Advanced Python
.

(2)上行遍历

.parent   节点的父亲标签
>>> soup.title.parent
<head><title>This is a python demo page</title></head>
>>> soup.parent
>>>
.parents  节点父辈标签,迭代类型
>>> for parent in soup.a.parents:
...     if parent is None:
...         print(parent)
...     else:
...         print(parent.name)
...

p
body
html
[document]

(3)平行遍历
在同一个父亲节点下的各节点间

.next_sibling   下一个平行节点标签
.next_siblings  迭代类型
>>> soup.a.next_sibling
u' and '
>>> soup.a.next_sibling.next_sibling
<a class="py2" href="http://www.icourse163.org/course/BIT-1001870001" id="link2">Advanced Python</a>
.previous_sibling   下一个平行节点标签
.previous_siblings  迭代类型
>>> soup.a.previous_sibling
u'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

四、格式输出

>>> demo
u'<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>'


>>> soup = BeautifulSoup(demo,'html.parser')
>>> soup.prettify()
u'<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>

五、内容查找方法

<>.find_all(name, attrs, recursive, string, **kwargs)

返回一个列表类型,存储查找的结果

name:对标签字符检索字符串

>>> soup.find_all('a')
[<a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">Basic Python</a>, <a class="py2" href="http://www.icourse163.org/course/BIT-1001870001" id="link2">Advanced Python</a>]
>>> soup.find_all(['a','b'])
[<b>The demo python introduces several python courses.</b>, <a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">Basic Python</a>, <a class="py2" href="http://www.icourse163.org/course/BIT-1001870001" id="link2">Advanced Python</a>]

>>> for tag in soup.find_all(True):
...     print(tag.name)
...
html
head
title
body
p
b
p
a
a

attrs:属性检索

>>> soup.find_all(id='link1')
[<a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">Basic Python</a>]

recursive:是否对子孙全部检索,默认为True

>>> soup.find_all('a')
[<a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">Basic Python</a>, <a class="py2" href="http://www.icourse163.org/course/BIT-1001870001" id="link2">Advanced Python</a>]
>>> soup.find_all('a',recursive=False)
[]

string:在<>…<>中检索字符串

>>> import re
>>> soup.find_all(string = re.compile('python'))
[u'This is a python demo page', u'The demo python introduces several python courses.']

六、世界大学定向排名爬虫

import requests
import bs4
from bs4 import BeautifulSoup


def getHTML(url):
   try:
       r = requests.get(url, timeout=20)
       r.raise_for_status()
       r.encoding = r.apparent_encoding
       return r.text
   except:
       return ""

def getInfo(ulist, text): 
    soup = BeautifulSoup(text, "html.parser")
    for tr in soup.find('tbody').children:
        if isinstance(tr, bs4.element.Tag):
            tds = tr('td')
            ulist.append([tds[0].string, tds[1].string, tds[4].string])

def printInfo(ulist, num): 
    temp = "{:^10}\t{:^6}\t{:^10}"
    print(temp.format("排名", "学校名称", "总分"))
    for i in range(num):
        u = ulist[i]
        print(temp.format(u[0], str(u[1]), u[2]))        

def main():
    url = "http://www.zuihaodaxue.com/ARWU2017.html"
    ulist = []
    num = 10    

    html = getHTML(url)
    getInfo(ulist, html)
    printInfo(ulist, num)

main()

效果
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值