将 html 转换为 url 抓取工具
Converting html to url scraper
一个非常乐于助人的人帮助我在 Whosebug 上取得了这么大的成就,但是我需要将他的代码从 HTMl 转换为 URL 来抓取我已经一遍又一遍地尝试并且我保留了遇到错误有什么想法吗?
function getElementByIdAsString($html, $id, $pretty = true) {
$doc = new DOMDocument();
@$doc->loadHTML($html);
if(!$doc) {
throw new Exception("Failed to load $url");
}
$element = $doc->getElementById($id);
if(!$element) {
throw new Exception("An element with id $id was not found");
}
// get all object tags
$objects = $element->getElementsByTagName('object'); // return node list
// take the the value of the data attribute from the first object tag
$data = $objects->item(0)->getAttributeNode('data')->value;
// cut away the unnecessary parts and return the info
return substr($data, strpos($data, '=')+1);
}
// call it:
$finalcontent = getElementByIdAsString($html, 'mainclass');
print_r ($finalcontent);
记得在使用函数时尝试捕获,因为它可能会抛出 Exception
s,这将导致 500 服务器错误。
$finalcontent = getElementByIdAsString($html, 'mainclass');
应该变成
try {
$finalcontent = getElementByIdAsString($html, 'mainclass');
}catch(Exception $e){
echo $e->getMessage();
}
一个非常乐于助人的人帮助我在 Whosebug 上取得了这么大的成就,但是我需要将他的代码从 HTMl 转换为 URL 来抓取我已经一遍又一遍地尝试并且我保留了遇到错误有什么想法吗?
function getElementByIdAsString($html, $id, $pretty = true) {
$doc = new DOMDocument();
@$doc->loadHTML($html);
if(!$doc) {
throw new Exception("Failed to load $url");
}
$element = $doc->getElementById($id);
if(!$element) {
throw new Exception("An element with id $id was not found");
}
// get all object tags
$objects = $element->getElementsByTagName('object'); // return node list
// take the the value of the data attribute from the first object tag
$data = $objects->item(0)->getAttributeNode('data')->value;
// cut away the unnecessary parts and return the info
return substr($data, strpos($data, '=')+1);
}
// call it:
$finalcontent = getElementByIdAsString($html, 'mainclass');
print_r ($finalcontent);
记得在使用函数时尝试捕获,因为它可能会抛出 Exception
s,这将导致 500 服务器错误。
$finalcontent = getElementByIdAsString($html, 'mainclass');
应该变成
try {
$finalcontent = getElementByIdAsString($html, 'mainclass');
}catch(Exception $e){
echo $e->getMessage();
}