Javascript 如何从外部url获取html源代码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5289027/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 16:29:36  来源:igfitidea点击:

How to get html source code from external url

javascriptjquery

提问by John

How can I get html source code from an external web page?

如何从外部网页获取 html 源代码?

Something like: getHtml('http://google.com');.

类似的东西:getHtml('http://google.com');

I've tried to get content of iframe using: $("#frame").contents().find("html");, but if in my case the webpage doesn't have html tags, just 1 line of text. I can't do it with php file_get_contents()because it doesn't keep session data.

我尝试使用: 获取 iframe 的内容$("#frame").contents().find("html");,但如果在我的情况下网页没有 html 标签,则只有 1 行文本。我不能用 php 来做,file_get_contents()因为它不保留会话数据。

采纳答案by mplungjan

Cross domain? not possible without a server process. If you are on windows and can use HTA you can use the iframe

跨域?没有服务器进程是不可能的。如果您在 Windows 上并且可以使用 HTA,则可以使用 iframe

回答by dialer

With javascript, getting the file contents from another domain is not allowed in many browsers for security reasons. In php, you'd have to utilize curl.

使用 javascript,出于安全原因,许多浏览器不允许从另一个域获取文件内容。在 php 中,您必须使用curl

For a workaround, you can make a php script with curl on your local domain and call that with javascript.

对于解决方法,您可以在本地域上使用 curl 制作一个 php 脚本,然后使用 javascript 调用它。

回答by Marwan

i think using javascript xmlhttprequest with setRequestHeader('content-type','xml/text') and the url what u need it will return the responseText as the html of the page

我认为使用带有 setRequestHeader('content-type','xml/text') 和 url 的 javascript xmlhttprequest 它将返回 responseText 作为页面的 html