python - 美丽汤 : <div class <span class></span><span class>TEXT I WANT</span>

标签 python

我正在尝试使用 BeautifulSoup 提取包含在 id="titleDescription"范围内的字符串。

<div class="itemText">
    <div class="wrapper">
        <span class="itemPromo">Customer Choice Award Winner</span>
        <a href="http://www.newegg.com/Product/Product.aspx?Item=N82E16819116501" title="View Details" >
            <span class="itemDescription" id="titleDescriptionID" style="display:inline">Intel Core i7-3770K Ivy Bridge 3.5GHz &#40;3.9GHz Turbo&#41; LGA 1155 77W Quad-Core Desktop Processor Intel HD Graphics 4000 BX80637I73770K</span>
            <span class="itemDescription" id="lineDescriptionID" style="display:none">Intel Core i7-3770K Ivy Bridge 3.5GHz &#40;3.9GHz Turbo&#41; LGA 1155 77W Quad-Core Desktop Processor Intel HD Graphics 4000 BX80637I73770K</span>
        </a>
    </div>

代码片段

f = open('egg.data', 'rb')
content = f.read()
content = content.decode('utf-8', 'replace')
content = ''.join([x for x in content if ord(x) < 128])

soup = bs(content)

for itemText in soup.find_all('div', attrs={'class':'itemText'}):
    wrapper = itemText.div
    wrapper_href = wrapper.a
    for child in wrapper_href.descendants:
        if child['id'] == 'titleDescriptionID':
           print(child, "\n")

回溯错误:

Traceback (most recent call last):
  File "egg.py", line 66, in <module>
    if child['id'] == 'titleDescriptionID':
TypeError: string indices must be integers

最佳答案

spans = soup.find_all('span', attrs={'id':'titleDescriptionID'})
for span in spans:
    print span.string

在您的代码中,wrapper_href.descendants 包含至少 4 个元素、2 个 span 标签和由 2 个 span 标签包围的 2 个字符串。它递归地搜索它的 child 。

关于python - 美丽汤 : <div class <span class></span><span class>TEXT I WANT</span>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17613606/

相关文章:

python - PIL 中的 PNG 显示在 OS X Mavericks 上损坏了吗?

python - 如何使用 Pygame 播放正弦波/方波?

python - 在 App Engine 上用 Python 打开图像

python - 为什么我的 Sprite 不经常出现,而不是静止不动时通过图像动画

python - 在外部文件中存储 unpicklabe pygame.Surface 对象

python - 使用递归计算列表的数量?

python - 需要有关以空格开头的正则表达式的帮助

python - 如何为没有 .py 文件扩展名的 Python 代码配置 .vimrc?

python - 如何对 pandas 中的字符串中的数字进行排序?

python - Django:摆脱内容类型的 RemovedInDjango19Warning