Как извлечь ссылки и заголовки из HTML-страницы? - PullRequest
26 голосов
/ 12 декабря 2010

для моего сайта, я хотел бы добавить новую функциональность.

Я бы хотел, чтобы пользователь мог загружать файл резервной копии своих закладок (из любого браузера, если это возможно), чтобы я мог загрузить его в своипрофиль, и им не нужно вставлять их все вручную ...

единственная часть, которую мне не хватает, чтобы сделать это, это часть извлечения заголовка и URL из загруженного файла .. может кто-нибудь датьподсказка с чего начать или где почитать?

использовала опцию поиска и ( как извлечь данные из необработанного html-файла ) это мой самый связанный вопрос, и он не говорит об этом ..

Я действительно не против, если он использует jquery или php

большое спасибо

Ответы [ 6 ]

55 голосов
/ 12 декабря 2010

Спасибо всем, я получил это!

окончательный код: здесь показан назначенный текст anchor и href для всех ссылок в файле .html

$html = file_get_contents('bookmarks.html');
//Create a new DOM document
$dom = new DOMDocument;

//Parse the HTML. The @ is used to suppress any parsing errors
//that will be thrown if the $html string isn't valid XHTML.
@$dom->loadHTML($html);

//Get all links. You could also use any other tag name here,
//like 'img' or 'table', to extract other tags.
$links = $dom->getElementsByTagName('a');

//Iterate over the extracted links and display their URLs
foreach ($links as $link){
    //Extract and show the "href" attribute.
    echo $link->nodeValue;
    echo $link->getAttribute('href'), '<br>';
}

СноваСпасибо большое.

33 голосов
/ 12 декабря 2010

Этого, вероятно, достаточно:

$dom = new DOMDocument;
$dom->loadHTML($html);
foreach ($dom->getElementsByTagName('a') as $node)
{
  echo $node->nodeValue.': '.$node->getAttribute("href")."\n";
}
5 голосов
/ 12 декабря 2010

При условии, что сохраненные ссылки находятся в html-файле, лучшим решением, вероятно, является использование html-парсера, такого как PHP Simple HTML DOM Parser (никогда не пробовал сам) (Другой вариант - поиск с использованием обычного поиска по строке или регулярного выражения, и вам, вероятно, никогда не следует использовать регулярное выражение для анализа html).

После прочтения html-файла с помощью парсера используйте его функции для поиска тегов a:

из учебника:

// Find all links
foreach($html->find('a') as $element)
       echo $element->href . '<br>'; 
3 голосов
/ 28 марта 2015

Это пример, вы можете использовать в вашем случае это:

$content = file_get_contents('bookmarks.html');

Запустите это:

<?php

$content = '<html>

<title>Random Website I am Crawling</title>

<body>

Click <a href="http://clicklink.com">here</a> for foobar

Another site is http://foobar.com

</body>

</html>';

$regex = "((https?|ftp)\:\/\/)?"; // SCHEME
$regex .= "([a-z0-9+!*(),;?&=\$_.-]+(\:[a-z0-9+!*(),;?&=\$_.-]+)?@)?"; // User and Pass
$regex .= "([a-z0-9-.]*)\.([a-z]{2,4})"; // Host or IP
$regex .= "(\:[0-9]{2,5})?"; // Port
$regex .= "(\/([a-z0-9+\$_-]\.?)+)*\/?"; // Path
$regex .= "(\?[a-z+&\$_.-][a-z0-9;:@&%=+\/\$_.-]*)?"; // GET Query
$regex .= "(#[a-z_.-][a-z0-9+\$_.-]*)?"; // Anchor


$matches = array(); //create array
$pattern = "/$regex/";

preg_match_all($pattern, $content, $matches); 

print_r(array_values(array_unique($matches[0])));
echo "<br><br>";
echo implode("<br>", array_values(array_unique($matches[0])));

Выход:

Array
(
    [0] => http://clicklink.com
    [1] => http://foobar.com
)

http://clicklink.com

http://foobar.com

1 голос
/ 08 января 2016
$html = file_get_contents('your file path');

$dom = new DOMDocument;

@$dom->loadHTML($html);

$styles = $dom->getElementsByTagName('link');

$links = $dom->getElementsByTagName('a');

$scripts = $dom->getElementsByTagName('script');

foreach($styles as $style)
{

    if($style->getAttribute('href')!="#")

    {
        echo $style->getAttribute('href');
        echo'<br>';
    }
}

foreach ($links as $link){

    if($link->getAttribute('href')!="#")
    {
        echo $link->getAttribute('href');
        echo'<br>';
    }
}

foreach($scripts as $script)
{

        echo $script->getAttribute('src');
        echo'<br>';

}
0 голосов
/ 20 марта 2019

Я хотел создать CSV путей ссылок и их текста со страниц HTML, чтобы я мог копировать меню и т. Д. С сайтов.

В этом примере вы указываете интересующий вас домен, поэтому вы не получаетевне ссылок сайта, а затем он создает CSV для каждого документа

/**
 * Extracts links to the given domain from the files and creates CSVs of the links
 */


$LinkExtractor = new LinkExtractor('https://www.example.co.uk');

$LinkExtractor->extract(__DIR__ . '/hamburger.htm');
$LinkExtractor->extract(__DIR__ . '/navbar.htm');
$LinkExtractor->extract(__DIR__ . '/footer.htm');

class LinkExtractor {
    public $domain;

    public function __construct($domain) {
      $this->domain = $domain;
    }

    public function extract($file) {
        $html = file_get_contents($file);
        //Create a new DOM document
        $dom = new DOMDocument;

        //Parse the HTML. The @ is used to suppress any parsing errors
        //that will be thrown if the $html string isn't valid XHTML.
        @$dom->loadHTML($html);

        //Get all links. You could also use any other tag name here,
        //like 'img' or 'table', to extract other tags.
        $links = $dom->getElementsByTagName('a');

        $results = [];
        //Iterate over the extracted links and display their URLs
        foreach ($links as $link){
            //Extract and sput the matching links in an array for the CSV
            $href = $link->getAttribute('href');
            $parts = parse_url($href);
            if (!empty($parts['path']) && strpos($this->domain, $parts['host']) !== false) {
                $results[$parts['path']] = [$parts['path'], $link->nodeValue];
            }
        }

        asort($results);
        // Make the CSV
        $fp = fopen($file .'.csv', 'w');
        foreach ($results as $fields) {
            fputcsv($fp, $fields);
        }
        fclose($fp);
    }
}
...