html結構是這樣的:
<strong>標題</strong>
<span>
內容
<a>子內容1</a><a>子內容2</a><a>子內容3</a>
內容1
<a>子內容1</a><a>子內容2</a><a>子內容3</a>
</span>
我獲取內容的xpath是這樣的:
content = html.xpath("//strong[text()='標題']/following-sibling::span/text()")[0]
這個xpath如果span標簽里面不存在那些a標簽,是可以獲取到內容的,但是如果有a標簽就不行了,請有a標簽的情況下如何處理呢?我想到的是先獲取到span標簽html.xpath("//strong[text()='標題']/following-sibling::span")[0],然后移除標簽里面的所有a標簽,然后再通過text()來獲取內容,但是不知道怎么寫。或者有其他思路?
uj5u.com熱心網友回復:
1、講道理直接 span/text() 是可以獲取內容和內容1的2、加個“ |“ 把兩種匹配都寫上
3、可以按照你的方法,先刪了a結點再匹配。
from lxml import html
string = ''' <strong>標題</strong>...'''
doc=html.fromstring(string)
doc.find('.//span/a').drop_tag()
洗掉后再匹配
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/226690.html
