使用PHP cURL从网站获取一些文本并存储在MySQL中

问题描述 投票:0回答:1

我已经寻找了一段时间以完成这项工作,但似乎我不能自己完成。我正在使用cURL从网站上获取一些信息,并将这些信息存储在MySQL数据库上。我现在所拥有的是以下代码:

$target_url = "[http:\[//\]iliria98\[.\]com][1]"; //delete [ and ] to get the url correctly
$userAgent = 'Googlebot/2.1 (http://www.googlebot.com/bot.html)';

// make the cURL request to $target_url
$ch = curl_init();
curl_setopt($ch, CURLOPT_USERAGENT, $userAgent);
curl_setopt($ch, CURLOPT_URL,$target_url);
curl_setopt($ch, CURLOPT_FAILONERROR, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_AUTOREFERER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch, CURLOPT_TIMEOUT, 100);
$html= curl_exec($ch);
if (!$html) {
    echo "<br />cURL error number:" .curl_errno($ch);
    echo "<br />cURL error:" . curl_error($ch);
    exit;
}

// parse the html into a DOMDocument
$document = new DOMDocument();
libxml_use_internal_errors(true);
$document->loadHTML($html);
libxml_clear_errors();
$selector = new DOMXPath($document);
//$anchors = $selector->query('//div[@class="single"]/div[2]');
$anchors = $selector->query('//div[@class="single"]/div');
foreach($anchors as $div) { 
    $text = $div->nodeValue;

    $valuta_arr=explode(',', $text);
    var_dump($valuta_arr);
    echo $text;
}

并且,输出结果不正确,因为它从网站获取了所有货币代码,但是货币值仅来自第一行(来自USD)。我想要的是从指定的url上的html表中获取值,并将这些值插入每种货币的数据库中,其中数据库表如下所示:

id
currency
sell
buy
date

我直到mysql插入代码才开始,因为我已经苦苦挣扎了3天时间才能首先从该网站获取信息。希望有人可以帮助我。谢谢大家。

php mysql curl web-scraping php-curl
1个回答
0
投票

[如果您尝试通过curl http://iliria98.com从控制台获取此页面,则会发现此小部件由js-script填充:

$('div#usd1').append('<div style="position: absolute; background: transparent; width: 100%; height: 100%; left: 0; top: 0; z-index: 9999;"></div>')
$(".kursiweb .single").eq(0).find("div").eq(1).html("114<sup>.20</sup>");  $(".kursiweb .single").eq(0).find("div").eq(2).html("116");

和其他...

因此,您只能从curl中获得的源HTML中的此脚本中获取所需数据,而不能从DOM文档中获得,只是因为curl没有任何JS引擎。

您可以使用的另一种方法-使用类似PhantomJS的东西>

© www.soinside.com 2019 - 2024. All rights reserved.