python – 在标签BeautifulSoup中显示文本
发布时间:2020-12-20 11:09:57 所属栏目:Python 来源:网络整理
导读:我试图只显示标签内的文字,例如: span class="listing-row__price "$71,996/span 我只想表现出来 “$71,996” 我的代码是: import requestsfrom bs4 import BeautifulSoupfrom csv import writerresponse = requests.get('https://www.cars.com/for-sale/s
我试图只显示标签内的文字,例如:
<span class="listing-row__price ">$71,996</span> 我只想表现出来
我的代码是: 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 即. 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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |