[英]How to ignore the <br> tag xpath
myList = tree.xpath('//div[@id="RM1127"]/div[@class="moreInfo"]/text()')
我正在為這個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看起來像這樣。 與其將“超過½磅的大蝦炸金酥”和“涼拌卷心菜,雞尾酒和塔塔醬”作為一個元素,不如將它們作為單獨的元素排列在一起。
使用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())
從文檔 :
lxml.html.HtmlElement.text_content():
返回元素的文本內容,包括其子元素的文本內容,不帶標記。
嘗試以下XPath表達式:
string(//div[@id="RM1127"]/div[@class="moreInfo"])
當應用於節點集時,XPath 字符串函數返回按文檔順序排在第一位的節點的字符串值。 元素節點的字符串值是所有文本節點后代的字符串值的串聯 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.