【问题标题】:What's the most efficient way to get this data, thousands of times?数千次获取这些数据的最有效方法是什么?
【发布时间】:2011-03-14 23:53:27
【问题描述】:

使用 PHP 的 DOMDocument->loadHTML() 系统获取以下数据(</b> 标记之后的 4.0m)的最佳方法是什么?我猜是某种 CSS 样式选择器?

(LINE 240, always 240) <b>Current Price:</b> 4.0m

我一直在查看文档,但老实说,这对我来说完全陌生!此外,我如何能够从以下 URL 获取数千个页面的数据:

http://site.com/q=item/viewitem.php?obj=11928

obj=# 的最小值/最大值是已知的(我需要抓取多少页),我想逐步抓取所有这些值,并输出 name descriptionprice(不是很关心目前的百分比上升/下降)到 MySQL 数据库,所以我可以从那里抓取它并在我的网站上显示它。

这是我感兴趣的主要代码块:

<div class="subsectionHeader"> 
<h2> 
Item Name
</h2> 
</div> 
<div id="item_additional" class="inner_brown_box">  
Description of item goes here.
<br> 
<br> 
<b>Current Price:</b> 4.0m
<br><br> 
<b>Change in Price:</b><br> 
<span> 
<b>30 Days:</b> <span class="rise">+2.5%</span> 
</span> 
<span class="spaced_span"> 
<b>90 Days:</b> <span class="drop">-30.4%</span> 
</span> 
<span class="spaced-span"> 
<b>180 Days:</b> <span class="drop">-33.3%</span> 
</span> 
<br class="clear"> 
</div> </div> <div class="brown_box main_page"> 
<div class="subsectionHeader"> `

如果有人可以提供有关如何进行此操作的任何基本提示,将不胜感激!

【问题讨论】:

标签: php html curl html-parsing scrape


【解决方案1】:

用正则表达式解析 HTML 通常是个坏主意,但在你的情况下,这可能是我正确/简单的方法。它足够快,可能比使用 strpos 和纯文本模式进行分块更灵活。

用上面给出的源 HTML 试试这个例子:

//checked with php 5.3.3
if (preg_match('#<h2>(?P<itemName>[^>]+)</h2>.*?<div[^>]+id=([\'"])item_additional(\2)[^>]*>\s*(?P<description>[^<]+).*?<b>\s*Current\s+Price\s?:?</b>\s*(?P<price>[^<]+)#six',$src, $matches))
{
    print_r($matches);
} 

正则表达式可能看起来太复杂了,但是有了文档和像 RegexBuddy 或 Expresso 这样的好工具,任何人都可以编写简单的表达式;)

【讨论】:

    【解决方案2】:

    您可以使用简单的 HTML DOM 解析器 - http://simplehtmldom.sourceforge.net/

    使用以下方法提取内容:

    echo file_get_html('http://www.google.com/')->plaintext; 
    

    然后使用 PHP str 函数定位 4.0m。

    【讨论】:

      【解决方案3】:

      DOM 解析是最可靠的方法。

      如果您想要最快的方式,并且知道 HTML 结构是一致的,那么使用strpos 搜索偏移量可能会更快。但是,如果页面结构发生变化,它更有可能中断。像这样的:

      $needles = array(
        'name' => "<div class=\"subsectionHeader\">\n<h2>\n"
        'description' => "<div id=\"item_additional\" class=\"inner_brown_box\">\n"
        'price' => "<b>Current Price:</b> "
      );
      $buffer = file_get_contents("http://site.com/q=item/viewitem.php?obj=1234");
      $result = array();
      foreach ($needles as $key => $needle) {
        $index1 = strpos($buffer, $needle);
        $index2 = strpos($buffer, "\n", $index1);
        $value = substr($buffer, $index1, $index2 - $index1);
        $result[$key] = $value;
      }
      

      您需要将指针完全正确,包括任何尾随空格。

      【讨论】:

        猜你喜欢
        • 2012-07-13
        • 2011-06-07
        • 1970-01-01
        • 2021-04-15
        • 2015-04-04
        • 2021-09-28
        • 2016-09-05
        • 2014-05-17
        • 1970-01-01
        相关资源
        最近更新 更多