javascript 如何使用 CasperJS 获取innerHTML?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32571765/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get innerHTML using CasperJS?
提问by Hyung Kyu Park
I want to get attribute of only string in <em>
tags of HTML page
我想在<em>
HTML 页面的标签中获取仅字符串的属性
I want to get "(868)"
我想得到“(868)”
1.
1.
casper.then(function() {
var word = require('utils').dump(this.getElementAttribute(x('//*[@id="content"]/div[2]/h4/em'), 'em'));
console.log(word)
});
2.
2.
casper.then(function() {
var word = require('utils').dump(this.getElementAttribute(h4[class="head"], 'em'));
console.log(word)
});
I tried both but it returns "null" How to solve the problem?
我都试过了,但它返回“null” 如何解决问题?
回答by Artjom B.
<em>
is not an element attribute. It's an element itself. casper.getElementAttribute(selector, attribute)
will correctly retrieve the attribute text of an element, but your want to get the element text.
<em>
不是元素属性。它本身就是一个元素。casper.getElementAttribute(selector, attribute)
将正确检索元素的属性文本,但您想要获取元素文本。
You can use casper.fetchText(selector)
for that. Note that fetchText()
will concatenate the contents of all matched elements into one string. If you don't want that, you either need to make sure that the selector only matches a single element or use other functions such as casper.getElementInfo(selector).text
.
你可以用casper.fetchText(selector)
它。请注意,这fetchText()
会将所有匹配元素的内容连接成一个字符串。如果您不希望那样,您要么需要确保选择器只匹配单个元素,要么使用其他函数,例如casper.getElementInfo(selector).text
.
Your second snippet cannot work, because you forgot "
around the selector and because of the above reason.
您的第二个代码段无法工作,因为您忘记"
了选择器以及上述原因。
回答by Zakaria Acharki
Take a look at documentation FAQ Can I access & manipulate DOM elements directly from the CasperJS environment?.
查看文档 FAQ我可以直接从 CasperJS 环境访问和操作 DOM 元素吗?.
In the both of examples that you added in your question you tried to get the em
element as an attribute of h4
and that wrong because em
is a child and not attribute of h4
tag, so to select textContent
of an element you can try to use querySelector
with evaluate
function like following :
在这两个例子,你在你的问题中新增了你试图让em
元素的属性h4
和错误的,因为em
是孩子,而不是属性h4
标签,因此选择textContent
,你可以尝试使用的元素querySelector
与evaluate
功能类似如下:
casper.then(function() {
var text = this.evaluate(function(){
return document.querySelector("h4.head em").textContent;
});
var word = require('utils').dump(text);
console.log(word);
}
Hope this helps.
希望这可以帮助。