正在使用PHP';s用于HTML抓取的explode()被认为是一种糟糕的做法


Is using PHP's explode() for HTML scraping considered a bad practice?

我已经编码了一段时间,但似乎无法理解正则表达式。

这就引出了我的问题:使用PHP的爆炸来分解一串html代码来选择文本片段是不是一种糟糕的做法?我需要在一页上抓取各种信息,由于我可怕的正则表达式知识(在一个完整的软件工程学位中,我不得不写一个……),我决定使用explode()。

我在下面提供了我的代码,所以比我经验更丰富的人可以告诉我是否需要使用regex!

public function split_between($start, $end, $blob)
{
    $strip = explode($start,$blob);
    $strip2 = explode($end,$strip[1]);
    return $strip2[0];
}
public function get_abstract($pubmed_id)
{
    $scrapehtml = file_get_contents("http://www.ncbi.nlm.nih.gov/m/pubmed/".$pubmed_id);
    $data['title'] = $this->split_between('<h2>','</h2>',$scrapehtml);
    $data['authors'] = $this->split_between('<div class="auth">','</div>',$scrapehtml);
    $data['journal'] = $this->split_between('<p class="j">','</p>',$scrapehtml);
    $data['aff'] = $this->split_between('<p class="aff">','</p>',$scrapehtml);
    $data['abstract'] = str_replace('<p class="no_t_m">','',str_replace('</p>','',$this->split_between('<h3 class="no_b_m">Abstract','</div>',$scrapehtml)));
    $strip = explode('<div class="ids">', $scrapehtml);
    $strip2 = explode('</div>', $strip[1]);
    $ids[] = $strip2[0];
    $id_test = strpos($strip[2],"PMCID");
    if (isset($strip[2]) && $id_test !== false)
    {
        $step = explode('</div>', $strip[2]);
        $ids[] = $step[0];
    }
    $id_count = 0;
    foreach ($ids as &$value) {
        $value = str_replace("<h3>", "", $value);
        $data['ids'][$id_count]['id'] = str_replace("</h3>", "", str_replace('<span>','',str_replace('</span>','',$value)));
        $id_count++;
    }
    $jsonAbstract = json_encode($data);
    echo $this->indent($jsonAbstract);
}

我强烈建议您试用PHP Simple HTML DOM Parser库。它处理无效的HTML,并被设计为解决您正在处理的相同问题

文档中的一个简单示例如下:

// Create DOM from URL or file
$html = file_get_html('http://www.google.com/');
// Find all images 
foreach($html->find('img') as $element) 
       echo $element->src . '<br>';
// Find all links 
foreach($html->find('a') as $element) 
       echo $element->href . '<br>';

对任何事情使用正则表达式都不是必不可少的,尽管熟悉它们并知道何时使用它们会很有用。

它看起来像是你在刮PubMed,我猜它在标记方面有相当静态的标记。如果您所做的工作和性能如您所希望的那样,我看不出有任何理由切换到使用正则表达式,那么在本例中,它们不一定会更快。

学习正则表达式,并尝试使用一种具有用于此类任务的库的语言,如perl或python。这会为你节省很多时间。起初,它们可能看起来令人生畏,但对于大多数任务来说,它们确实很容易。请尝试阅读以下内容:http://perldoc.perl.org/perlre.html

相关文章: