Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/75.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用XPathJavaScript获取innerHTML?_Javascript_Html_Xpath - Fatal编程技术网

如何使用XPathJavaScript获取innerHTML?

如何使用XPathJavaScript获取innerHTML?,javascript,html,xpath,Javascript,Html,Xpath,我需要从内部元素中检索文本。有了php,使用Xpath变得非常简单。用javascript怎么样?我也需要从具有特定id的特定元素中检索。下面代码下的请求。假设CORS没有问题。我安装了chrome扩展来解决CORS <html> <head> </head> <body> <script> fetch('https://alexistogel1.blogspot.com/2019/08/post-tak-penting.

我需要从内部元素中检索文本。有了php,使用Xpath变得非常简单。用javascript怎么样?我也需要从具有特定id的特定元素中检索。下面代码下的请求。假设CORS没有问题。我安装了chrome扩展来解决CORS

<html>
<head>
</head>
<body>


<script>


   fetch('https://alexistogel1.blogspot.com/2019/08/post-tak-penting.html')
    .then(function (response) {
      return response.text();
    })
    .then(function (html) {
      var element = document.evaluate( "//div[@id='post-body-6034358444211110141']" ,document, null, XPathResult.ANY_TYPE, null );
      console.log(element);
    });
</script>
</body>
</html>

取('https://alexistogel1.blogspot.com/2019/08/post-tak-penting.html')
.然后(功能(响应){
返回response.text();
})
.then(函数(html){
var element=document.evaluate(//div[@id='post-body-6034358442111110141'],document,null,XPathResult.ANY_TYPE,null);
控制台日志(元素);
});
使用a将字符串转换为
文档

现在,您可以使用
文档
getElementById
的帮助下选择其中的元素

fetch('https://alexistogel1.blogspot.com/2019/08/post-tak-penting.html')
    .then(function (response) {
        return response.text();
    })
    .then(function (text) {
        const parser = new DOMParser();
        return parser.parseFromString(text, 'text/html');
    })
    .then(function (html) {
        var element = html.getElementById('post-body-6034358444211110141');
        console.log(element.innerHTML);
    });

您是被迫使用XPath的吗?不,所有的解决方案都是接受的。
document.evaluate
be
html
?@EmielZuurbier我也试过了,在“document”上执行“evaluate”失败时出错:参数2不是“Node”类型,我给出的错误类似于enum。然后我将application/html更改为text/html来修复。但在itry
控制台日志(element.stringValue)时给出其他错误
stringValue
不是
元素
包含的属性。您需要获取
innerHTML
属性来获取元素中的值。我已经更新了答案。Xpath解决方案返回未定义。我已经删除了Xpath答案,因为它似乎不起作用
getElementById
是一个本机JavaScript函数,它是选择元素的更好方法。