rom*_*the 5 html python beautifulsoup
我有一小段HTML,我想通过BeautifulSoup运行.我已经有了基本的导航功能,但这个让我很难过.
这是HTML的一个示例(完全构成):
<div class="textbox">
Buying this item will cost you
<img align="adsbottom" alt="1" src="/1.jpg;type=symbol"/>
silver credits and
<img align="adsbottom" alt="1" src="/1.jpg;type=symbol"/>
golden credits
</div>
Run Code Online (Sandbox Code Playgroud)
使用img标签的'alt'属性我希望看到以下结果: 购买此项目将花费您1银奖和1金奖
我不知道如何顺序循环遍历div-tag.我可以执行以下操作来提取div-tag中包含的所有文本
html = BeautifulSoup(string)
print html.get_text()
Run Code Online (Sandbox Code Playgroud)
获取div标签中包含的所有文本,但这会给我这样的结果: 购买此项目将花费您银奖和金币
同样,我可以通过这样做从img-tags获取alt属性的值:
html = BeautifulSoup(string).img
print html['alt']
Run Code Online (Sandbox Code Playgroud)
但当然这只给了我属性值.
如何以正确的顺序迭代所有这些元素?是否可以按连续顺序读取div元素中的文本和img-element的属性?
您可以遍历标记的所有子项,包括文本; 测试他们的类型,看看他们是Tag或NavigableString对象:
from bs4 import Tag
result = []
for child in html.find('div', class_='textbox').children:
if isinstance(child, Tag):
result.append(child.get('alt', ''))
else:
result.append(child.strip())
print ' '.join(result)
Run Code Online (Sandbox Code Playgroud)
演示:
>>> from bs4 import BeautifulSoup, Tag
>>> sample = '''\
... <div class="textbox">
... Buying this item will cost you
... <img align="adsbottom" alt="1" src="/1.jpg;type=symbol"/>
... silver credits and
... <img align="adsbottom" alt="1" src="/1.jpg;type=symbol"/>
... golden credits
... </div>
... '''
>>> html = BeautifulSoup(sample)
>>> result = []
>>> for child in html.find('div', class_='textbox').children:
... if isinstance(child, Tag):
... result.append(child.get('alt', ''))
... else:
... result.append(child.strip())
...
>>> print ' '.join(result)
Buying this item will cost you 1 silver credits and 1 golden credits
Run Code Online (Sandbox Code Playgroud)