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

4
如何仅选择容器内的文本,而不获取子元素的文本?例如,如何选择下面HTML中的文本Toshiba Satellite Pro C850-1GR Satellite Pro, 1.8 GHz

我的尝试

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个回答

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中有这个数据表的简短摘要,那么你可以尝试以下方法:

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代码,但我找到了你想要爬取的网站。我不确定具体是哪个页面,所以这是我找到并完成的内容。如果你访问这个页面,你可以在其中找到与你问题中相同的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

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

我在文档中有多个工具提示文本类别,所以它对我返回了错误的区域。 - Ninja2k
它有简短的摘要描述。 - Ninja2k
我更新了我的答案。如果这仍然不起作用,请尝试找到另一种模式。 - 4d4c
好的,那么你唯一的选择就是发布整个HTML。 - 4d4c
整个HTML文件非常庞大!如果你想试着处理它,我可以将它通过电子邮件发送给你? - Ninja2k
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接