ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

python_bs对象的select()方法

2022-01-19 15:33:17  阅读:214  来源: 互联网

标签:获取 python 标签 指定 soup bs print select


准备

导包并以这段HTML源码为例,创建一个bs对象。

from bs4 import BeautifulSoup
html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><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>
"""
soup = BeautifulSoup(html_doc, 'lxml')

获取所有<a>标签

print(soup.select('a'))

在这里插入图片描述输出结果为一个列表


获取class属性为指定值的标签

筛选出class='sister’的标签:
在指定class属性值前加点符号表示class:

print(soup.select('.sister'))

在这里插入图片描述


获取id属性为指定值的标签

筛选出id值为link1的标签:
在指定的id属性值前加井号表示id:

print(soup.select('#link1'))

在这里插入图片描述


获取指定文本

  • .string()
  • .get_text()
# 获取title标签当中的文本
print(soup.select('title'))
print('_'*100)
print(soup.select('title')[0].string)
print('_'*100)
print(soup.select('title')[0].get_text()) 

输出结果:
在这里插入图片描述


获取指定标签的指定属性:

获取所有<a>标签的href属性

a_tag = soup.select('a')
for i in a_tag:
    print(i['href'])

(i是标签对象,i.href不管用。)
在这里插入图片描述

标签:获取,python,标签,指定,soup,bs,print,select
来源: https://blog.csdn.net/weixin_48964486/article/details/122580607

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有