【问题标题】:Text between tag including the text of children within the tag in lxml标记之间的文本,包括 lxml 中标记内子项的文本
【发布时间】:2014-11-28 12:19:05
【问题描述】:

您好,我想要标签中的所有文本,但在该 td 标签内有多个子标签,例如 .

>>>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 等其他库。干杯

【问题讨论】:

    标签: python python-2.7 lxml


    【解决方案1】:

    text 属性仅返回该元素中的文本,但 text_content method 返回元素中包含的所有文本或其子元素

    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 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-26
      • 1970-01-01
      • 2012-09-18
      • 2013-01-10
      • 2017-02-16
      • 1970-01-01
      • 2020-03-09
      • 1970-01-01
      相关资源
      最近更新 更多