【问题标题】:Scraping with Simple HTML DOM Parser使用简单的 HTML DOM 解析器进行抓取
【发布时间】:2012-09-23 10:29:40
【问题描述】:

您好,我正在尝试使用 Simple HTML DOM Parser 抓取 UFC 赛事日程。

我正在努力选择正确的数据。

我想要标题、图片、日期、时间和地点。

到目前为止我已经尝试过

function scraping_ufc() {
    // create HTML DOM
    $html = file_get_html('http://uk.ufc.com/schedule/event/');

    // get news block
    foreach($html->find('table tr') as $event) {
        // get title
        $item['title'] = trim($event->find('div[class="event-tagline"]', 0)->innertext);
        // get details
        $item['date'] = trim($event->find('div[class="date"]', 0)->innertext);

        $item['time'] = trim($event->find('div[class="time"]', 0)->innertext);

        $ret[] = $item;
    }


    // clean up memory
    $html->clear();
    unset($html);

    return $ret;
}

选择了很多不需要的表格行,我确实设法获得了标题,但没有获得日期或时间。

请帮我有效地选择我需要的数据。

【问题讨论】:

  • 虽然它违反了他的网站使用条款,但不要这样做。

标签: php screen-scraping simple-html-dom


【解决方案1】:

首先,停止使用简单的 html dom,因为它不如内置的 dom 库可靠。几年前它很有用,但现在它确实导致的问题比它解决的要多。

$dom = new DOMDocument();
@$dom->loadHTMLFile('http://uk.ufc.com/schedule/event/');
$xpath = new DOMXPath($dom);

接下来,您需要一种更好的方法来识别所需的行。 table tr 将选择页面上的每个 tr 并且您不希望这样。如果 tr 有样式就好了,但它们不是,所以我想出了这个:

foreach($xpath->query('//td[@class="upcoming-events-image"]/..') as $tr){
  $item['title'] = $xpath->query('.//div[@class="event-tagline"]/a', $tr)->item(0)->nodeValue;
  $item['date'] = $xpath->query('.//div[@class="date"]', $tr)->item(0)->nodeValue;
  $item['time'] = $xpath->query('.//div[@class="time"]', $tr)->item(0)->nodeValue;
  $ret[] = $item;
}

【讨论】:

    猜你喜欢
    • 2015-01-07
    • 2016-02-22
    • 2015-07-25
    • 1970-01-01
    • 2011-08-02
    • 2014-03-18
    • 1970-01-01
    • 2015-12-04
    • 1970-01-01
    相关资源
    最近更新 更多