我正试图提取用^{id1}括起来的跨度所包含的字符串$
<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 (3.9GHz Turbo) 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 (3.9GHz Turbo) 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
wrapper_href.descendants
包含任何^{NavigableString
本质上是字符串对象,您试图用child['id']
行来索引它:为什么不直接使用
itemText.find('span', id='titleDescriptionID')
加载标记呢?演示:
在代码中,
wrapper_href.descendants
至少包含4个元素、2个span标记和2个由2个span标记括起的字符串。它递归地搜索它的子对象。当我们使用BeautifulSoup搜索标记时,我们得到一个BeautifulSoup.tag对象,它可以直接用于访问其其他属性,如内部内容、样式、ref等
相关问题 更多 >
编程相关推荐