Я хотел бы найти все якоря со страницы, которые НЕ вложены курсивом. Это то, что у меня есть, и он работает, но ссылки не обрабатываются в правильном порядке (в соответствии с источником страницы)PHP XPath Query
@$dom->loadHTML($this->html);
$xpath = new DOMXpath($dom);
$anchorlinks = $xpath->query('//a/@href[not(. = //i//a/@href)]');
Любые советы о том, как я должен перейти к дифф два набора в xpath запрос был бы весьма признателен.
Спасибо.
$phil = gettingToPhilosophy("http://en.wikipedia.org/Yarn");
for($i=0; $i<30; $i++)
{
$phil->hop();
$phil->processHTML();
}
<?php
class gettingToPhilosophy
{
public $base_url; //base_url to start with
public $target_url; //url to hop to
public $previous_link; //keep track of last link
public $lookup; //cached array of visited links
public $curl; //curl object to execute
public $html; //html retrieved from curl request
public $conn; //database connection resource
public $hoplimit; //maximum number of hops (23 was the median as per the wikipedia article)
public $hop_num; //the number of hops taken to reach the philosophy page
public $id; //id of current link (Primary Key)
public $child_id; //id of next link
function __construct($base_url)
{
$this->base_url = filter_var($base_url, FILTER_VALIDATE_URL);
//determine if url is valid
if (!($this->base_url))
{
die("<font color='red'>Invalid URL</font>");
}
$this->target_url = parse_url($base_url, PHP_URL_PATH);
$this->previous_link = '';
$this->lookup = array();
$this->curl = curl_init();
// Create a user agent as to not get blocked by wikipedia
$userAgent = 'Googlebot/2.1 (http://www.google.bot.com/bot.html)';
// Initialize curl and following options
//curl_setopt($this->curl, CURLOPT_USERAGENT, $userAgent);
//curl_setopt($this->curl, CURLOPT_FAILONERROR, true);
//curl_setopt($this->curl, CURLOPT_FOLLOWLOCATION, true);
//curl_setopt($this->curl, CURLOPT_AUTOREFERER, true);
//curl_setopt($this->curl, CURLOPT_RETURNTRANSFER,true);
//curl_setopt($this->curl, CURLOPT_TIMEOUT, 10);
//$this->conn = pg_connect("dbname=Wesley user=Wesley host=localhost") or die("Can't connect to database".pg_last_error());
$this->hoplimit = 30;
$this->hop_num = 0;
$this->id = 1;
$this->child_id = 0;
}
function __destruct()
{
$this->base_url = null;
$this->target_url = null;
$this->previous_link = null;
$this->curl = null;
$this->lookup = null;
//pg_close($this-conn);
$this->conn = null;
$this->id = null;
$this->child_id = null;
}
function hop()
{
//Error handling for cached results of links
if (isset($this->lookup[$this->target_url]))
{
//printLinks();
die("<font color='red'>Never ending loop: $this->target_url has already been seen</font>");
}
$this->lookup[$this->target_url] = 1; //cache the link
$this->child_id++;
$sql = "insert into Philosophy (base_url, childid, link) values('$this->base_url', $this->child_id, '$this->target_url')";
//pg_execute($conn,$sql);
echo "$sql <br/>";
//append nodeValue to wikipedia url scheme
$this->target_url = "http://en.wikipedia.org".$this->target_url;
// Reset url
$userAgent = 'Googlebot/2.1 (http://www.google.bot.com/bot.html)';
// Initialize curl and following options
curl_setopt($this->curl, CURLOPT_USERAGENT, $userAgent);
curl_setopt($this->curl, CURLOPT_FAILONERROR, true);
curl_setopt($this->curl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($this->curl, CURLOPT_AUTOREFERER, true);
curl_setopt($this->curl, CURLOPT_RETURNTRANSFER,true);
curl_setopt($this->curl, CURLOPT_TIMEOUT, 10);
curl_setopt($this->curl, CURLOPT_URL,$this->target_url);
// Get html from the page
$this->html = curl_exec($this->curl);
// Error handling for invalid link
if(!$this->html)
{
//$this->printLinks();
//target_url was invalid or not reachable
die("<font color='red'>$this->target_url is invalid or unreachable - Hopped $this->hop_num times</font>");
}
$this->hop_num++;
}
function processHTML()
{
$dom = new DOMDocument();
@$dom->loadHTML($this->html);
$xpath = new DOMXpath($dom);
$anchorlinks = $xpath->query('//a[not(ancestor::i)]/@href');
//$anchorlinks = $dom->getElementsByTagName('a');
echo "<pre>"; print_r(iterator_to_array($anchorlinks)); echo "</pre>"; exit;
foreach($anchorlinks as $anchorlink)
{
if (!$this->isValid($anchorlink->nodeValue)){ continue; }
$this->previous_link = $this->target_url;
$this->target_url = "$anchorlink->nodeValue";
$flag = true;
break;
/*foreach($anchorlink->attributes as $attribute)
{
//skip erroneous links
if ($attribute->nodeName !== 'href') {continue;}
if (!$this->isValid($attribute->nodeValue)){ continue; }
$this->target_url = "$attribute->nodeValue";
$flag = true;
break;
}*/
}
}
function isValid($link)
{
if ($link === $this->previous_link){ return false; }
//links to ignore
if (strstr($link, '#') || stristr($link, 'Help:') || stristr($link, 'navigation') || stristr($link,'[note')
|| strstr($link, '(') || stristr($link, 'File:') || strstr($link, '.jpg') || strstr($link, '?') || stristr($link, 'http')
|| strstr($link, '//') || stristr($link, 'Portal:') || stristr($link, 'Special:') || stristr($link, 'Wikipedia:')
|| stristr($link, 'Talk:') || stristr($link, 'Category:') || stristr($link, 'Main_Page'))
{
return false;
}
return true;
}
function printLinks()
{
$sql = "select childid, link from philosophy where base_url='$this->base_url'";
if ($result = pg_execute($conn, $sql))
{
while ($row = pg_fetch_assoc($result))
{
echo "{$row['childid']}) {$row['link']} <br/>";
}
}
}
}
?>
Спасибо !! http://en.wikipedia.org/wiki/Wikipedia:Getting_to_Philosophy Я пытаюсь решить эту проблему, но, к сожалению, ваш запрос xpath не обрабатывает ссылки в правильном порядке ... какие-либо дополнительные советы? – Wes
Содержит ли xpath узлы в другом порядке? – Wes
@Wes Добро пожаловать. Скорее всего, ваш движок Xpath поддерживает только XPath 1.0. В версии 1.0 узлы определены как _sets_ (позвольте мне также указать вам на [страницу Wiki] (http://en.wikipedia.org/wiki/Set_%28mathematics%29)), что означает, что нет особого порядка для их. Но все же, двигатели часто возвращают результаты в порядке документа. Вам нужно будет показать весь ваш PHP-код, а также опубликовать полученный результат, иначе все ставки будут отключены. –