python 标签之间文本_python – 在标签BeautifulSoup中显示文本

要获取标记内的文本,有几种方法,

a)使用标记的.text属性.

cars = soup.find_all('span',attrs={'class': 'listing-row__price'})

for tag in cars:

print(tag.text.strip())

产量

$71,996

$75,831

$71,412

$75,476

....

for tag in cars:

print(tag.get_text().strip())

c)如果标签内只有该字符串,您也可以使用这些选项

> .string

> .contents [0]

>下一个(tag.children)

> next(tag.strings)

> next(tag.stripped_strings)

即.

for tag in cars:

print(tag.string.strip()) #or uncomment any of the below lines

#print(tag.contents[0].strip())

#print(next(tag.children).strip())

#print(next(tag.strings).strip())

#print(next(tag.stripped_strings))

输出:

$71,476

$77,001

...

注意:

.text和.string不一样.如果标记中有其他元素,则.string返回None,而.text将返回标记内的文本.

from bs4 import BeautifulSoup

html="""

hello there

"""

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

p = soup.find('p')

print(p.string)

print(p.text)

输出

None

hello there

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值