【问题标题】:Web Scrape using php curl使用 php curl 进行网页抓取
【发布时间】:2014-11-01 06:10:15
【问题描述】:

我有一个包含以下代码的 html 页面。现在我只想在本地页面中以 json 格式打印名称和位置。

<div class='post-header'>
<div class='post-header-line-1'></div>
</div>
<div class='post-body entry-content' id='post-body-210098160524748093'   itemprop='articleBody'>
<div class="separator" style="clear: right; float: right; margin-bottom: 1em; margin-left: 1em; text-align: center;">
<br /></div>


<br />
<br />
<ul>
<li>Name<br />Location</li>
<li>Name<br />location</li>
<li>name<br />location</li>
<li>name<br />location</li>
</ul>
<br />

输出应该是这样的,任何建议都会有所帮助。

{
"contacts": [
    {
            "id": "1",
            "name": "Name",
            "location":"location"
    },
    {
            "id": "2",
            "name": "Name",
            "location":"location"
    }
]
}

【问题讨论】:

  • 通过 curl 加载页面,然后使用 DOMDocument,然后将节点值收集到一个数组中,最后使用 json 编码

标签: php html json curl web-scraping


【解决方案1】:

你可以抓取&lt;li&gt;&lt;/li&gt;元素的内容,用&lt;br /&gt;分割它们,然后使用jQuery生成JSON,然后使用jQuery POST请求方法将其传递给PHP:

$().ready(function() {
    var storeLocations = new Array();
    var storeName = new Array();

    $("li").each(function() {
        var content = $(this).text().split('<br />');
        storeName[storeName.length] = content[0];
        storeLocation[storeLocation.length] = content[1];
    });

    var jsonString = '{["contacts:["';

    for(var i = 0; i < storeLocations.length; i++) {
        jsonString += '{"id:' + i + ', "name:"' + storeName[i] + '", "location:"' + storeLocation[i] + '"},';
    }

    jsonString += "]]}";
    var url = "form.php";

    $.post(url, jsonString);
});

http://api.jquery.com/jquery.post/

【讨论】:

  • jquery 标签不包含在问题中,但无论如何,无需手动构建 json 字符串,只需使用 JSON.stringify(javascript_object),如果你想要一个 json 字符串,或者只是整个对象,然后让 PHP 解码它
  • 我明白,我不知道如何使用 PHP 直接从页面中抓取页面元素,所以我提出了下一个想到的想法。感谢您的信息。
【解决方案2】:

另一种方法是使用正则表达式

<?php

$re = '/<li>([a-zA-Z]+)<br \/>([a-zA-Z]+)<\/li>/m';
$str = '<li>Name<br />Location</li>
<li>Name<br />location</li>
<li>name<br />location</li>
<li>name<br />location</li>';

preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);

$arrayOfResults = [];

foreach($matches as $n => $match) {
    $arrayOfResults["contacts"][] = [
        "id" => $n + 1,
        "name" => $match[1], 
        "location" => $match[2]
    ];
   
}

$json = json_encode($arrayOfResults);

var_dump($json);

这里是 regex101:

https://regex101.com/r/0Hx6qD/1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-17
    • 2017-11-20
    • 2012-06-12
    • 2015-02-27
    • 1970-01-01
    • 1970-01-01
    • 2020-11-07
    • 2018-02-06
    相关资源
    最近更新 更多