2014-12-13 98 views
2

如何获得question第一,下划线和最后一部分的文本,并将其存储到一个变量,使用分裂?分裂:获取XPATH文本块是不是唯一的要素

见底部的HTML。我想作以下变量具有以下值:

first_part = "Jingle bells, jingle bells, jingle all the" 
second_part = "_______" 
third_part = "! Oh what fun it is to ride in one-horse open sleigh!" 

我去here,使用的XPath

//*[@id="question_container"]/div[1]/span/text()[1] #this is first_part 
//*[@id="question_container"]/div[1]/span/span  #this is second_part 
//*[@id="question_container"]/div[1]/span/text()[2] #this is third_part 

,并将其应用到下面的HTML。他们回到在测试通缉值,但对于我的程序,斯普林特似乎拒绝他们:

first_part = browser.find_by_xpath(xpath = '//*[@id="question_container"]/div[1]/span/text()[1]').text 
second_part = browser.find_by_xpath(xpath = '//*[@id="question_container"]/div[1]/span/span').text 
third_part = browser.find_by_xpath(xpath = '//*[@id="question_container"]/div[1]/span/text()[2]').text 

print first_part 
print second_part 
print third_part 

-------------- OUTPUT  ------------- 

[] 
[] 
[] 

我在做什么错了,为什么错了,我应该怎么更改我的代码?

的参照的HTML(其轻微地被编辑为“铃儿响叮当”,以更好地传达该问题),使用分裂的browser.html特征被检索:

<div id="question_container" style="display: block;"> 
<div class="question_wrap"> 

<span class="question">Jingle bells, jingle bells, jingle all the 
<span class="underline" style="display: none;">_______</span> 
<input type="text" name="vocab_answer" class="answer" id="vocab_answer"></input> 
! Oh what fun it is to ride in one-horse open sleigh!</span> 

</div></div> 

回答

1

xpath传递给find_by_xpath()方法必须指向/结果到元素,而不是文本节点。

一个办法是找到外span,得到它的html和饲料它lxml.html

from lxml.html import fromstring 

element = browser.find_by_xpath(xpath='//div[@id="question_container"]//span[@class="question"]') 

root = fromstring(element.html) 
first_part = root.xpath('./text()[1]')[0] 
second_part = root.xpath('./span/text()')[0] 
third_part = root.xpath('./text()[last()]')[0] 

print first_part, second_part, third_part 

打印:

Jingle bells, jingle bells, jingle all the 
_______ 
! Oh what fun it is to ride in one-horse open sleigh! 
+0

什么时候使用,而不是'find_by_xpath()'什么?我在Splinter的文档中找不到其他相关方法。 – 2014-12-13 03:11:22

+0

@Princee你应该找到'类=“问题”'第一'span'。然后,你可以得到文本的各个部分,肯定有多个选项。你能提供一个链接到我的网站测试?谢谢。 – alecxe 2014-12-13 03:12:22

+0

@Princee感谢,请尝试在更新后的答案的解决方案。 – alecxe 2014-12-13 03:34:50