问题描述
我想通过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