Python爬虫学习 5 —— 使用BeautifulSoup提取信息

一、信息标记的三种形式

XML:eXtensible Markup Language
1、特点

  • 类似HTML,使用标签
  • 允许有注释

2、例子

<person>
  <firstName>Tian</firstName>
  <lastName>Song</lastName>
  <address>
    <streetAdder>中关村</streetAdder>
    <city>北京市</city>
    <zipcode>100081</zipcode>
  </address>
  <prof>Computer System</prof><prof>Security</prof>
</person>

JSON:JavaScript Object Notation
1、特点

  • 有类型的键值对:"key": "value"
  • 多值使用 "name": ["key1", "key2"]
  • 键值对嵌套使用 {}

2、例子

{
  "firstName": "Tian"
  "lastName" : "Song"
  "address"  : {
                  "streetAdder": "中关村",
                  "city"       : "北京市",
                  "zipcode"    : "100081"
                },
  "prof"     :  ["computer System", "Security"]
}

YAML:YAML Ain’t Markup Language
1、特点

  • 无类型的键值对:name: value
  • 多值使用缩进 tab
  • - 表达并列关系

2、例子

firstName : Tian
lastName  : Song
address   :
    streetAdder : 中关村
    city        : 北京市
    zipcode     : 100081
prof
-computer System
-Security

对比

XML:最早的通用信息标记语言,可扩展性好,但繁琐
XML:信息有类型,适合程序处理
XML:信息无类型,文本信息比例最高,可读性好



二、信息提取

我们试试提取一个HTML文件乱码的所有链接:

思路
1、搜索所有的<a>标签
2、解析<a>标签,提取href后的链接内容

实现

import requests
from bs4 import BeautifulSoup

url = "http://python123.io/ws/demo.html"
r = requests.get(url)
soup = BeautifulSoup(r.text, "html.parser")

for link in soup.find_all("a"):
	print(link.get("href"))

提取结果:

http://www.icourse163.org/course/BIT-268001
http://www.icourse163.org/course/BIT-1001870001


三、使用bs4库的HTML内容查找方法

find_all()
语法:find_all(name, attrs, recursive, string, **kwargs)
返回值:返回一个列表类型,存储查询结果
参数:参考文档

参数名说明
name对标签名称的检索字符串
attrs对标签属性的检索字符串,可标注属性检索
recursive是否对子孙全部检索,默认值为True
string<> … </>字符串区域的检索字符串
limit设自治允许返回的列表长度

find_all的使用

1、检索标签名:

import requests
from bs4 import BeautifulSoup

url = "http://python123.io/ws/demo.html"
r = requests.get(url)
soup = BeautifulSoup(r.text, "html.parser")

print(soup.find_all("a"))
print(soup.find_all(["a", "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>]
[<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>]

2、设置检索所有子孙节点

import requests
from bs4 import BeautifulSoup

url = "http://python123.io/ws/demo.html"
r = requests.get(url)
soup = BeautifulSoup(r.text, "html.parser")

for tag in soup.find_all(True):
	print(tag.name)

检索结果:

html
head
title
body
p
b
p
a
a
***Repl Closed***

3、使用正则表达式查询以b开头的标签

import requests, re
from bs4 import BeautifulSoup

url = "http://python123.io/ws/demo.html"
r = requests.get(url)
soup = BeautifulSoup(r.text, "html.parser")

for tag in soup.find_all(re.compile("b")):
	print(tag.name)

查询结果:

body
b

4、根据CSS属性来检索:

import requests, re
from bs4 import BeautifulSoup

url = "http://python123.io/ws/demo.html"
r = requests.get(url)
soup = BeautifulSoup(r.text, "html.parser")

# 查询class属性值为"py1"的标签
for tag in soup.find_all("a", class_="py1"):
	print(tag)

# 查询class属性值为"py2"的标签
for tag in soup.find_all("a", attrs={"class": "py2"}):
	print(tag)

# 查询含有 id 属性的所有标签
for tag in soup.find_all(id=True):
	print(tag)

# 查询 id 属性值为 "link1" 的标签
for tag in soup.find_all(id="link1"):
	print(tag)

输出:

<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>
<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>
<a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">Basic Python</a>

5、设置recursive值为False

import requests, re
from bs4 import BeautifulSoup

url = "http://python123.io/ws/demo.html"
r = requests.get(url)
soup = BeautifulSoup(r.text, "html.parser")

print(soup.find_all("a", recursive=False))

查询结果:说明:<a>标签不存在于soup的子标签中,但存在域子孙节点中

[]

6、根据字符串内容来查找

import requests, re
from bs4 import BeautifulSoup

url = "http://python123.io/ws/demo.html"
r = requests.get(url)
soup = BeautifulSoup(r.text, "html.parser")

print(soup.find_all(string="Basic Python"))
print(soup.find_all(string=re.compile("python")))

查询结果:

['Basic Python']
['This is a python demo page', 'The demo python introduces several python courses.']

替代find_all:可以使用下面的方法替代find_all()函数

<tag>.(...) = <tag>.find_all()
soup(...) = soup.find_all()



三、查找的扩展方法
方法说明(参数同find_all())
<>.find()搜索且只返回第一个结果,字符串类型
<>.find_parents()在先辈节点中搜索,返回列表类型
<>.find_parent()在先辈节点中搜索,返回字符串类型
<>.find_next_siblings()在后续平行节点中搜索,返回列表类型
<>.find_next_siblings()在后续平行节点中搜索,返回字符串类型
<>.find_previous_siblings()在前续平行节点中搜索,返回列表类型
<>.find_previous_siblings()在前续平行节点中搜索,返回字符串类型

更多详细信息可以查看Beautiful Soup文档




第五篇python爬虫学习笔记完结啦 cheers ??

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值