在标签 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)

如何从标签中提取文本?

原文由 R K 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 548
2 个回答

要获取标签中的文本,有几种方法,

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]
  • next(tag.children)
  • next(tag.strings)
  • next(tag.stripped_strings)

IE。

 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,996
$75,831
$71,412
$75,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

原文由 Bitto Bennichan 发布,翻译遵循 CC BY-SA 4.0 许可协议

print( [x.text for x in cars] )

原文由 C8H10N4O2 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题