您好我想要标签中的所有文字,但在该标签内有多个子标签,如。
>>>import urllib2
>>>from lxml import etree
>>>import lxml
>>>site = "http://racing.racingnsw.com.au/InteractiveForm/HorseAllForm.aspx?HorseCode=ODA0ODQ0MTUy&src=horsesearch"
>>>req = urllib2.Request(site)
>>>page = urllib2.urlopen(req)
>>>content = page.read()
>>>root = etree.HTML(content)
>>>s = root.xpath('//*[@id="info-container"]/table[2]/tr[%s]/td[2]/text()'%'34')
>>>s
[' 1800m Good3 PETER YOUNG STK Group 2 $222,000 ($134,000) ', ' 59kg Barrier 5 Rtg 118 ', ' 2nd ', ' 59kg, 3rd ', ' 59kg 1:50.09 (600m 34.92), 0.1L, 7th@800m, 6th@400m, $2/$2.15/$2.15']
我想要子标签的文本以及td标签,但我当前的lxml并不是为我做的。 相反,我希望看到:
['RAND 31Jan14', ' 1300m Dead BT-4UEGOPN $000 ', 'Tommy Berry', ' 0kg Barrier 0 ', ' 1st ', 'Glencadam Gold (IRE)', ' 0kg, 3rd ', 'The Offer (IRE)', ' 0kg 1:20.90, 1L ', '\n']
或更喜欢该列表的字符串和连接表示:
'RAND 31Jan14 1300m Dead BT-4UEGOPN $000 Tommy Berry 0kg Barrier 0 1st Glencadam Gold (IRE) 0kg, 3rd The Offer (IRE) 0kg 1:20.90, 1L'
我尝试过使用etree.tostring(xpath,method =" text")并查看文档但没有运气
我想专门用lxml工作,所以请不要使用其他图书馆,比如Beautiful Soup。干杯
答案 0 :(得分:3)
text
属性仅返回该Element中的文本,但是
text_content
method返回Element 或其子级中包含的所有文本:
import urllib2
import lxml.html as LH
site = "http://racing.racingnsw.com.au/InteractiveForm/HorseAllForm.aspx?HorseCode=ODA0ODQ0MTUy&src=horsesearch"
req = urllib2.Request(site)
page = urllib2.urlopen(req)
root = LH.parse(page)
for td in root.xpath('//*[@id="info-container"]/table[2]/tr[33]/td[2]'):
print(td.text_content())
产量
RAND 31Jan14 1300m Dead BT-4UEGOPN $000 Tommy Berry 0kg Barrier 0 1st Glencadam Gold (IRE) 0kg, 3rd The Offer (IRE) 0kg 1:20.90, 1L