Python通过CSS选择器获取span值

问题描述

我想通过CSS选择器提取范围值

soup = BeautifulSoup("<body><main><div class='rentalprice'><span>3.000</span></div></main></body>")
pagecontent = soup.find('body')

price = pagecontent.main.div.span.text # this line works although it's not suitable for production since I've now ignored the div class selector

#I then tried this:
price = pagecontent.select('main div.rentalprice span').text

最后一行抛出错误:

发生异常:AttributeError。 ResultSet对象没有属性“文本”。您可能会像对待单个元素一样对待一系列元素。当您打算致电find()时,您是否致电过find_all()?

我该如何解决?我不想使用for循环,因为只有1个跨度可以匹配。

我已经检查过: How to get text from span tag in BeautifulSoup Get value of attribute using CSS Selectors with BeutifulSoup Python Selenium CSS Selector by Span get_attribute

解决方法

gl = newlist() 返回元素列表,但是您只能在单个元素上使用listsort(gl)

如果您确定只有1个跨度匹配,则可以定位select返回的列表中的第一个元素:

.text

否则,您可以使用for循环:

select
,

使用.find()

from bs4 import BeautifulSoup

soup = BeautifulSoup("<body><main><div class='rentalprice'><span>3.000</span></div></main></body>",'html.parser')
pagecontent = soup.find('body')
price = pagecontent.find('span').text
print(price) # 3.000

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...