使用Beautiful Soup时删除html标签的问题

时间:2012-12-19 10:16:25

标签: python python-2.7 beautifulsoup

我正在使用漂亮的汤来从网站上抓取一些数据,但我无法在打印时从数据中删除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标签。请原谅我的无知,因为我是编程新手。

1 个答案:

答案 0 :(得分:0)

您正在打印找到的标签。要仅打印包含的文本,请使用.string属性:

print anchor1.string

.string值为NavigableString instance;像普通的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