美丽的汤 - 打印容器文本而不打印子元素的文本

时间:2013-08-27 20:07:20

标签: python html beautifulsoup

如何在不获取子元素文本的情况下定位容器中的文本?例如,我如何定位文本Toshiba Satellite Pro C850-1GR Satellite Pro, 1.8 GHz 在下面的HTML

我的尝试

short_description=soup.find('div',{'class':'info-item description product-short-desc c_both'}).text
print short_description

HTML

<div id="product-short-summary-wrap">
<b class="tip-anchor tip-anchor-wrap">Short summary description Toshiba Satellite Pro C850-1GR</b>ev
:
<br/>
<div class="tooltip-text">This short summary of the data-sheet.</div>
 Toshiba Satellite Pro C850-1GR Satellite Pro, 1.8 GHz
</div>

1 个答案:

答案 0 :(得分:2)

选择上面的div元素并使用nextSibling

from bs4 import BeautifulSoup

html = '<div id="product-short-summary-wrap">\
<b class="tip-anchor tip-anchor-wrap">Short summary description Toshiba Satellite Pro C850-1GR</b>ev\
:\
<br/>\
<div class="tooltip-text">This short summary of the data-sheet.</div>\
 Toshiba Satellite Pro C850-1GR Satellite Pro, 1.8 GHz\
</div>'

soup = BeautifulSoup(html)

text = soup.find("div", {"class":"tooltip-text"})
print text.nextSibling.string

输出:

Toshiba Satellite Pro C850-1GR Satellite Pro, 1.8 GHz

如果div中包含This short summary of the data-sheet,那么您可以尝试:

from bs4 import BeautifulSoup

html = '<div id="product-short-summary-wrap">\
<b class="tip-anchor tip-anchor-wrap">Short summary description Toshiba Satellite Pro C850-1GR</b>ev\
:\
<br/>\
<div class="tooltip-text">This short summary of the data-sheet.</div>\
 Toshiba Satellite Pro C850-1GR Satellite Pro, 1.8 GHz\
</div>'

soup = BeautifulSoup(html)

text = soup.find("div", {"class":"tooltip-text"})
if "This short summary of the data-sheet." in text.string:
        print text.nextSibling.string

输出:

Toshiba Satellite Pro C850-1GR Satellite Pro, 1.8 GHz

我认为您在PasteBin中发布了错误的HTML,但我找到了您要废弃的网站。我不确定这个页面到底是什么,我已经找到并完成了。如果您转到此page,则可以找到与问题相同的HTML部分。我提取文本的代码:

import urllib2
from bs4 import BeautifulSoup

url = "http://icecat.biz/p/toshiba/pscbxe-01t01gfr/satellite-pro-notebooks-4051528036589-C8501GR-17411822.html"
html = urllib2.urlopen(url)

soup = BeautifulSoup(html)

texts = soup.findAll("div", {"class":"tooltip-text"})
for text in texts:
    if text.string:
        if "This short summary of the" in text.string:
            print text.nextSibling.string.strip() 

输出:

Toshiba C850-1GR Satellite Pro, 1.8 GHz, Intel Celeron, 1000M, 4 GB, DDR3-SDRAM, 1600 MHz

不同的URL同样的事情,输出:

Intel H2312WPFJR, Socket R (2011), Intel, Xeon, 2048 GB, DDR3-SDRAM, 2048 GB

如果需要,可以在找到后拆分字符串