Python 美丽的汤发现-只得到文本

Python 美丽的汤发现-只得到文本,python,web,beautifulsoup,Python,Web,Beautifulsoup,我有一段代码把价格作为一个字符串(125.01)输出,但我一定做了一些更改,因为现在它打印了整行的html标记和所有内容。如何让它只打印文本而不使用正则表达式 import requests from bs4 import BeautifulSoup url = 'http://finance.yahoo.com/q?s=aapl&fr=uh3_finance_web&uhb=uhb2' data = requests.get(url) soup = BeautifulSou

我有一段代码把价格作为一个字符串(125.01)输出,但我一定做了一些更改,因为现在它打印了整行的html标记和所有内容。如何让它只打印文本而不使用正则表达式

import requests
from bs4 import BeautifulSoup

url = 'http://finance.yahoo.com/q?s=aapl&fr=uh3_finance_web&uhb=uhb2'

data = requests.get(url)
soup = BeautifulSoup(data.content)
price = soup.find("span", {'id':'yfs_l84_aapl'})
print(price)


<span id="yfs_l84_aapl">125.01</span>
导入请求
从bs4导入BeautifulSoup
url='1〕http://finance.yahoo.com/q?s=aapl&fr=uh3_finance_web&uhb=uhb2'
data=requests.get(url)
soup=BeautifulSoup(data.content)
price=soup.find(“span”,{'id':'yfs_l84_aapl'})
印刷品(价格)
125.01
您必须调用
price
变量的方法:

print(price.get_text())
在汤标签上使用
get_text()

print(price.get_text())

有时我发现
.text
.get_text()
返回一个空字符串,我必须使用:

打印(price.contents[0])


我认为这与返回的unicode与字节有关。

或者可能是
price.text
。不同之处在于,如果
span
有时具有HTML格式(例如,红色表示负数),
text
将包含所有子标记的文本,而
get_text()
仅返回即时文本。如果您不希望发生这种情况,
get_text()
可能就是您想要的。感谢您快速准确的回答!谢谢你快速准确的回答!解决了的。我添加了.get_text()方法,它成功了。谢谢@halex