python – Beautiful Soup – 打印容器文本而不打印子元素的文本

如何在不获取子元素文本的情况下定位容器中的文本?例如,我如何定位文本东芝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>

最佳答案 选择上面的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有这个数据表的简短摘要,那么你可以试试这个:

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

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

点赞