python爬虫小白入门教科书_Python爬虫小白入门(十)Python 爬虫 – BeautifulSoup分析页面...

我们已经抓取了一个HTML页面,接下来,我们使用BeautifulSoup来分析页面。

importrequestsfrom bs4 importBeautifulSoup

page= requests.get("https://kevinhwu.github.io/demo/python-scraping/simple.html")

soup= BeautifulSoup(page.content, 'html.parser')

导入BeautifulSoup库,创建页面解析对象soup。

前面打印出的html页面格式很乱,如果想打印出美化格式的html页面,可以使用BeautifulSoup对象上的prettify方法:

print(soup.prettify())

输出

A simple example page

Hereis some simple content forthis page.

html文档解析后,文档中的html元素构成一个树形结构。可以使用BeautifulSoup对象上的children属性(类型是list_iterator),访问页面的顶层元素。

list(soup.children)

输出

['html', '\n',

A simple example page

Hereis some simple content forthis page.

, '\n']

可以看到,页面顶层有2个元素:

初始标签

标签

列表中还有2个换行符(\n)。可以看一下列表中元素的类型是什么:

[type(item) for item in list(soup.children)]

输出

[, , , ]

如上所示,所有对象都是BeautifulSoup中的对象:

bs4.element.Doctype – Doctype对象,包含关于文档类型的信息

bs4.element.Tag – Tag对象,表示html 标签,对象中会嵌套其他标签

bs4.element.NavigableString – 表示HTML文档中的文本,此处是指2个换行符文本的类型

Tag对象是最重要的对象类型,是我们最常打交道的对象类型。Tag对象让我们可以遍历,提取HTML文档中的标签和文本。

返回HTML文档顶层子节点的第3个节点,即标签。

html = list(soup.children)[2]

返回的节点html也是一个BeautifulSoup对象,因此可以继续访问该节点的子节点:

list(html.children)

输出

['\n',

A simple example page

, '\n',

Hereis some simple content forthis page.

, '\n']

可以看到,忽略换行符,这里有2个标签,head和body。

尝试提取p标签中的文本,先找到body:

body = list(html.children)[3]

获取body标签的子标签:

list(body.children)

输出

['\n',

Hereis some simple content forthis page.

, '\n']

提取p标签:

p = list(body.children)[1]

得到p标签后,就可以使用get_text方法来提取标签内的文本:

importrequestsfrom bs4 importBeautifulSoup

page=requests.get("https://kevinhwu.github.io/demo/python-scraping/simple.html")

soup=BeautifulSoup(page.content,'html.parser')#print(soup.prettify())

html = list(soup.children)[2]

body= list(html.children)[3]

p= list(body.children)[1]print(p.get_text())

输出

C:\Anaconda3\python.exe "C:\Program Files\JetBrains\PyCharm 2019.1.1\helpers\pydev\pydevconsole.py" --mode=client --port=54852

import sys; print('Python %s on %s' %(sys.version, sys.platform))

sys.path.extend(['C:\\app\\PycharmProjects', 'C:/app/PycharmProjects'])

Python3.7.6 (default, Jan 8 2020, 20:23:39) [MSC v.1916 64bit (AMD64)]

Type'copyright', 'credits' or 'license' formore information

IPython7.12.0 -- An enhanced Interactive Python. Type '?' forhelp.

PyDev console: using IPython7.12.0

Python3.7.6 (default, Jan 8 2020, 20:23:39) [MSC v.1916 64bit (AMD64)] on win32

runfile('C:/app/PycharmProjects/ArtificialIntelligence/test2.py', wdir='C:/app/PycharmProjects/ArtificialIntelligence')

Hereis some simple content for this page.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值