-1

我正在使用以下引用的代码从网站上抓取一些项目名称:

# -*- coding: cp1252 -*-
import csv
import urllib2
import sys
import time
from bs4 import BeautifulSoup

page = urllib2.urlopen('http://www.vodafone.de/privat/tarife/red-smartphone-tarife.html').read()
soup = BeautifulSoup(page)
soup.prettify()
items = soup.findAll('div', {"class": "txtBox"})
for item in items:
    print unicode(item.string).encode('utf8').strip()

问题:当我运行此代码时,将打印 18 个“无”而不是 18 个项目的名称。

输出片段:

>>> 
None
None
None
None
None
None
None
None
None
None
4

1 回答 1

0

您真的想先仔细看看您匹配的内容,这些是更复杂的 HTML 结构,而不仅仅是简单的标签:

>>> items = soup.findAll('div', {"class": "txtBox"})
>>> items[0]
<div class="txtBox">
<h3>iPhone 5</h3>
<div class="pr-stars" style="background-position: 0px -108px">
</div>
<div class="details">
<select id="color">
<option value="4">Weiß</option>
<option selected="selected" value="5">Schwarz</option>
</select>
<select id="size">
<option value="4">16 GB</option>
<option selected="selected" value="5">32 GB</option>
<option value="6">64 GB</option>
</select>
<ul>
<li>8 Megapixel-Kamera</li><li>A6 Chip</li><li>112 Gramm leicht</li></ul>
<div class="price">
<span id="price"><br/>
</span></div>
</div>
<div class="button">
<a class="vfmodal-trigger" href="#">Details </a>
</div>
</div>

您可能想要获取包含<H3>标签的值,如果有的话:

for item in items:
    h3tag = item.find('h3')
    if h3tag is not None:
        print unicode(h3tag.string).encode('utf8').strip()
于 2012-12-28T14:30:07.980 回答