>我正在使用漂亮的汤从网站上抓取一些数据,但我无法在打印数据时从数据中删除html标签。引用的代码是:
import csv
import urllib2
import sys
from bs4 import BeautifulSoup
page = urllib2.urlopen('http://www.att.com/shop/wireless/devices/smartphones.html').read()
soup = BeautifulSoup(page)
soup.prettify()
for anchor1 in soup.findAll('div', {"class": "listGrid-price"}):
print anchor1
for anchor2 in soup.findAll('div', {"class": "gridPrice"}):
print anchor2
for anchor3 in soup.findAll('div', {"class": "gridMultiDevicePrice"}):
print anchor3
我使用它获得的输出如下所示:
<div class="listGrid-price">
$99.99
</div>
<div class="listGrid-price">
$0.01
</div>
<div class="listGrid-price">
$0.01
</div>
我只想要输出中的价格,周围没有任何 html 标签。请原谅我的无知,因为我是编程新手。
您正在打印找到的标记。若要仅打印包含的文本,请使用 .string
属性:
print anchor1.string
.string
值是一个NavigableString
实例;要像普通的 unicode 对象一样使用它,请先转换它。然后您可以使用strip()
删除多余的空格:
print unicode(anchor1.string).strip()
稍微调整一下以允许空值:
for anchor1 in soup.findAll('div', {"class": "listGrid-price"}):
if anchor1.string:
print unicode(anchor1.string).strip()
这给了我:
$99.99
$0.99
$0.99
$299.99
$199.99
$49.99
$49.99
$99.99
$0.99
$99.99
$0.01
$0.01
$0.01
$0.01
$0.01