【问题标题】:Extract data from HTML tag从 HTML 标签中提取数据
【发布时间】:2017-12-26 06:31:55
【问题描述】:

我有以下代码并试图从 html 页面中提取属性内容的值,但它没有给出我期望的任何结果,而是只给出空白页。

任何帮助可能是哪里的问题?

$url= "https://fr-ca.wordpress.org";
$html = file_get_contents($url);
  # Create a DOM parser object
   $dom = new DOMDocument();
   $dom->loadHTML($html);
   foreach ($dom->getElementsByTagName('meta') as $key ) {
   echo "<pre>";
   $tab[] = $key->getAttribute('content');
   }
   $reg= '<meta name="generator" content="(.*?)"/>';
   if (preg_match_all($reg, $html, $ar)) {
    print_r($ar);
   } 

页面来源有:

<meta name="generator" content="WP 4.5"/>

【问题讨论】:

  • 我想你想打印 $ar 而不是 $tab。我相信 preg_match 参数是正则表达式、来源、结果。
  • 不应将正则表达式用于HTML 抓取
  • @DarkBee 不确定它是否太离题,但你能推荐用于 HTML 抓取的最佳通用方法吗?
  • 只使用你的示例代码中的 dom 解析器?

标签: php html extract


【解决方案1】:

试试这个:

$html = '<meta name="generator" content="WP 4.5"/>';
preg_match_all('/content="(.*)"/i', $html, $matches);
if (isset($matches[1])) {
    print_r($matches[1]);
}

【讨论】:

  • 嗨@smoqadam,谢谢你的回答,实际上情况是不同的,因为每个网站都会有不同的输出,如上例所示:如果我打印匹配,我有坐索引$match[1][4],但如果我更改 URL,我将需要打印不同的索引 $match[1][x]。如何解决这个问题。
  • 使用php-simple-html-dom-parsersymfony.com/doc/current/components/dom_crawler.html 可能会更好
【解决方案2】:

这是一个查找元标记并获取内容属性内容的正则表达式。它有一些通配符可以解释其他变量,例如不同的名称或额外的空格等。

$html = '<meta name="generator" content="WP 4.5"/>';

preg_match_all( '#<meta.*?content=[\'"](.*?)[\'"]\s*/>#i', $tab, $results );
print_r( $results[1] ); // contains array of captures.
if( $results[1] ) {
    // code here...
}

【讨论】:

  • 非常感谢,这正是我想要的 :) preg_match_all( '# #i', $html, $results );
【解决方案3】:

请这样使用...

$html = file_get_contents( $url);

    libxml_use_internal_errors( true);
    $doc = new DOMDocument;
    $doc->loadHTML( $html);
    $xpath = new DOMXpath( $doc);

    // A name attribute on a <div>???
    $nodes = $xpath->query( '//div[@name="changeable_text"]')->item( 0);

    echo $nodes->Content; 

// 使用卷曲 ...

function getHTML($url,$timeout)
{
       $ch = curl_init($url); // initialize curl with given url
       curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER["HTTP_USER_AGENT"]); // set  useragent
       curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // write the response to a variable
       curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // follow redirects if any
       curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); // max. seconds to execute
       curl_setopt($ch, CURLOPT_FAILONERROR, 1); // stop when it encounters an error
       return @curl_exec($ch);
}
$html=getHTML("http://www.website.com",10);
// Find all images on webpage
foreach($html->find("img") as $element)
echo $element->src . '<br>';

// Find all links on webpage
foreach($html->find("a") as $element)
echo $element->href . '<br>';

【讨论】:

猜你喜欢
  • 2021-10-22
  • 2019-04-04
  • 2018-05-07
  • 1970-01-01
  • 2015-11-17
  • 1970-01-01
  • 1970-01-01
  • 2010-10-17
  • 2020-01-07
相关资源
最近更新 更多