如何忽略<br>标记 xpath


myList = tree.xpath('//div[@id="RM1127"]/div[@class="moreInfo"]/text()')

我正在抓取这个div内的元素的网站。它工作得很好,但在这个div上,有一个<b>标签。myList将该div的元素作为两个独立的元素返回。

<div class="moreInfo" style="display:none;font-weight:normal; font-size:14px; margin-top:6px; padding:0px 0 0 30px;">
    Over ½ lb. of jumbo shrimp fried golden crisp in a…
    <br></br>
    coleslaw, cocktail & Tartar sauce. …
</div>

html看起来像这样。而不是"超过半磅的大虾炒成金黄脆"one_answers"凉拌卷心菜,鸡尾酒&;作为一个元素,我将它们都作为数组中的单独元素。

使用Python XPath + LXML,只需调用HtmlElement.text_content()。看一下这个完整的例子:

from lxml import etree
import lxml.html    
html  ="""<!DOCTYPE html>
<html>
<body>
    <div id="RM1127">
        <div class="moreInfo" style="">
            Over 1/2 lb. of jumbo shrimp fried golden crisp in a...
            <br>
            coleslaw, cocktail & Tartar sauce
        </div>
    </div>
</body>
</html>"""
dom = lxml.html.fromstring(html)
tags = dom.xpath("""//div[@id="RM1127"]/div[@class="moreInfo"]""")
for e in tags:
    print(e.text_content())

From doc:

lxml.html.HtmlElement.text_content ():
返回元素的文本内容,包括其子元素的文本内容,不带任何标记。

尝试下面的XPath表达式:

string(//div[@id="RM1127"]/div[@class="moreInfo"])

当应用于节点集时,XPath字符串函数返回文档顺序中第一个节点的字符串值。元素节点的字符串值是所有文本节点后代的字符串值的连接。

如果使用scrapy并且不想使用lxml.html,那么我找不到任何其他方法,而不是使用regex来删除这样的br标签。scrapy文档response = response.replace(body = re.sub(b'</?s*s*brs*/?s*>',b'',response.body))谁有更好的方法,请分享。

最新更新