javascript 从 URL 获取 div 的内容
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9093146/
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
Get contents of a div from a URL
提问by amit
Possible Duplicate:
How to implement a web scraper in PHP?
How to parse and process HTML with PHP?
I need to crawl through a page and get the contents of a particular div. I have php and javascript as my two main options. How can it be done?
我需要爬过一个页面并获取特定 div 的内容。我有 php 和 javascript 作为我的两个主要选择。怎么做到呢?
采纳答案by Mike
This is quite a basic method to do it PHP and it returns the content in plain text. However you might consider revising the regex for your particular need.
这是一个非常基本的 PHP 方法,它以纯文本形式返回内容。但是,您可能会考虑根据您的特定需要修改正则表达式。
<?php
$link = file_get_contents("http://www.domain.com");
$file = strip_tags($link, "<div>");
preg_match_all("/<div/>(?:[^<]*)<\/div>/is", $file, $content);
print_r($content);
?>
回答by Sabari
There are many ways to get the contents of an url:
有很多方法可以获取 url 的内容:
First Method:
第一种方法:
http://simplehtmldom.sourceforge.net/
http://simplehtmldom.sourceforge.net/
Simple HTML DOM Parser
Second Method :
第二种方法:
<?php
$contents = file_get_contents("http://www.url.com");
$contents = strip_tags($contents, "<div>");
preg_match_all("/<div/>(?:[^<]*)<\/div>/is", $contents, $file_contents);
?>
Third Method:
第三种方法:
`You can use jquery like Selectors :`
回答by jerjer
You can use SimpleDomParser as documented here http://simplehtmldom.sourceforge.net/manual.htmit requires PHP5+ though, but the nice thing is you can find tags on an HTML page with selectors just like jQuery.
您可以使用此处记录的 SimpleDomParser http://simplehtmldom.sourceforge.net/manual.htm虽然它需要 PHP5+,但好处是您可以在带有选择器的 HTML 页面上找到标签,就像 jQuery。
回答by Chris Kempen
Specifically with jQuery, if you have a div
like the following:
特别是使用 jQuery,如果您有div
以下类似的内容:
<div id="cool_div">Some content here</div>
You could use jQuery to get the contents of the div
like this:
您可以使用 jQuery 来获取这样的内容div
:
$('#cool_div').text(); // will return text version of contents...
$('#cool_div').html(); // will return HTML version of contents...
If you're using PHP to generate the content of the page, then you should be able to get a decent handle on the content and manipulate it even before it's returned to the screen and displayed. Hope this helps!
如果您使用 PHP 来生成页面的内容,那么您应该能够很好地处理内容并在它返回到屏幕并显示之前对其进行操作。希望这可以帮助!
回答by Franquis
Using PHP, you can try the DOMDocumentclass and the getElements()function
使用 PHP,你可以试试DOMDocument类和getElements()函数