在标签 BeautifulSoup 内显示文本 [英] Show text inside the tags BeautifulSoup
本文介绍了在标签 BeautifulSoup 内显示文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图只显示标签内的文本,例如:
I'm trying to show only the text inside the tag, for example:
<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)
如何从标签中提取文本?
How can I extract the text from the tags?
推荐答案
要获取标签内的文本,有几种方法,
To get the text within the tags, there are a couple of approaches,
a) 使用标签的 .text
属性.
a) Use the .text
attribute of the tag.
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) 如果标签内只有那个字符串,你也可以使用这些选项
c) If there is only that string inside the tag, you can use these options also
.string
.contents[0]
next(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,996
$75,831
$71,412
$75,476
$77,001
...
注意:
.text
和 .string
不一样.如果标签中有其他元素,.string
返回 None
,而 .text 将返回标签内的文本.
.text
and .string
are not the same. If there are other elements in the tag, .string
returns the None
, while .text will return the text inside the tag.
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
这篇关于在标签 BeautifulSoup 内显示文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文