[英]How to get text of child element
On this page , I want to enter "looked" or "gone", click the "spaCy Word Lemmatize" button, and then find the "Analysis Result" on the resulting page.在这个页面上,我想输入“looked”或“gone”,点击“spaCy Word Lemmatize”按钮,然后在结果页面上找到“Analysis Result”。 I have the code to do everything but I can't isolate the result.我有代码可以做所有事情,但我无法隔离结果。
Original Text Analysis Result
------------- ---------------
looked look
gone go
This is the HTML result for 'looked':这是“looked”的 HTML 结果:
<div class="span5 offset1">
<h4>Original Text</h4>
<p>
looked
</p>
</div>
<div class="span5">
<h4>Analysis Result</h4>
<p>
look
</p>
</div>
This is my code这是我的代码
array = []
myText = ["looked", "gone"] # I post this array to website.
for a in range(0, len(myText)):
x = driver.find_element_by_class_name("span5")
array.append(x.text)
print b -> [u'Original Text\nlooked', u'Original Text\ngone']
How can I get only the result, "look" or "go"?我怎样才能只得到结果,“看”或“去”?
Answer is: locate all elements containing specific class and child p tag答案是:定位包含特定类和子 p 标签的所有元素
element = driver.find_element_by_xpath('//div[contains(@class, 'span5')]/p')
text = element.text
You can also use the following CSS Selector for that:您还可以为此使用以下 CSS 选择器:
...
text = driver.find_element_by_css_selector(".span5>p").text
...
You can optimize your code:您可以优化您的代码:
array = []
elements = driver.find_elements_by_css_selector(".span5>p")
for element in elements:
array.append(element.text)
or more Pythonic:或更多 Pythonic:
array = [element.text for element in elements]
Hope it helps you!希望对你有帮助!
As you post the following array to website:当您将以下数组发布到网站时:
myText = ["looked", "gone"]
As per the resulten HTML DOM to extract the texts eg look , go etc, you can use the following solution:根据生成的HTML DOM提取文本,例如look 、 go等,您可以使用以下解决方案:
my_elements = driver.find_elements_by_css_selector("div.span5:not(.offset1) p")
my_array = [my_element.text for my_element in my_elements]
print(my_array)
I'm assuming that div elements are childs of another entity, this is in Java maybe you know how to make it in Python.我假设 div 元素是另一个实体的子元素,这是在 Java 中,也许您知道如何在 Python 中制作它。 I created a list of WebElements based on className and a tagName - in your case p tag, after that I'm printing the results.我创建了一个基于 className 和 tagName 的 WebElements 列表 - 在你的例子中是 p 标签,之后我正在打印结果。
List<WebElement> listofWords= driver.findElement(By.className("other_entity_ClassName_or_something_else")).findElements(By.tagName("p"));
for (int i = 0; i < listofWords.size(); i++) {
System.out.println(listofWords.get(i).getText());
}
Thanks,谢谢,
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.