微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

python – 在标签BeautifulSoup中显示文本

我试图只显示标签内的文字,例如:

<span class="listing-row__price ">$71,996</span>

我只想表现出来

“$71,996”

我的代码是:

import requests
from bs4 import BeautifulSoup
from csv import writer

response = requests.get('https://www.cars.com/for-sale/searchresults.action/?mdId=21811&mkId=20024&page=1&perPage=100&rd=99999&searchSource=PAGINATION&showMore=false&sort=relevance&stkTypId=28880&zc=11209')

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

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

我哪里错了?

解决方法

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

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
....

b)使用get_text()

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="""
<p>hello <b>there</b></p>
"""
soup = BeautifulSoup(html,'html.parser')
p = soup.find('p')
print(p.string)
print(p.text)

输出

None
hello there

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐