出於學習目的,我試圖從Steam商店獲取數據,如果圖像game_header_image_full
存在,我已經達到了遊戲。兩種替代方法都是有效的,但有一個問題。一個非常慢,另一個似乎錯過了一些數據,因此不會將URL寫入文本文件。preg_match在使用cURL獲取數據時丟失了一些ID
出於某種原因,簡單的HTML DOM設法抓住了9個URL,而第二個(cURL)只抓住了8個帶有preg_match的URL。
問題1.
是$reg
的方式,$html->find('img.game_header_image_full')
會趕上格式化的,但不是我的preg_match
?還是其他問題呢?
問題2:
我在這裏做的事情是否正確?打算去cURL的替代品,但我能以某種方式加快速度嗎?
簡單的HTML DOM解析器(時間來搜索100個IDS:1分鐘,39S返回:9 URL)
<?php
include('simple_html_dom.php');
$i = 0;
$times_to_run = 100;
set_time_limit(0);
while ($i++ < $times_to_run) {
// Find target image
$url = "http://store.steampowered.com/app/".$i;
$html = file_get_html($url);
$element = $html->find('img.game_header_image_full');
if($i == $times_to_run) {
echo "Success!";
}
foreach($element as $key => $value){
// Check if image was found
if (strpos($value,'img') == false) {
// Do nothing, repeat loop with $i++;
} else {
// Add (don't overwrite) to file steam.txt
file_put_contents('steam.txt', $url.PHP_EOL , FILE_APPEND);
}
}
}
?>
與捲曲替代..(時間來搜索100個IDS:34S返回的:8 URL。)
<?php
$i = 0;
$times_to_run = 100;
set_time_limit(0);
while ($i++ < $times_to_run) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://store.steampowered.com/app/'.$i);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$content = curl_exec($ch);
$url = "http://store.steampowered.com/app/".$i;
$reg = "/<\\s*img\\s+[^>]*class=['\"][^'\"]*game_header_image_full[^'\"]*['\"]/i";
if(preg_match($reg, $content)) {
file_put_contents('steam.txt', $url.PHP_EOL , FILE_APPEND);
}
}
?>
http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags我會只是把這個留在這裏。 – AlexanderMP
@AlexanderMP我是一個磨砂,這種作品。我很抱歉。 –
不,我明白。我使用這樣的正則表達式比我想承認的要多。但是,當它有時因爲一些愚蠢的原因而失敗時,不要感到驚訝。您必須手動瀏覽100個HTML頁面,找出哪一個應匹配,哪些不匹配。我的意思是肯定的,正則表達式很快,並且可以節省高達60%的時間,但它不能正常工作,這就是爲什麼您使用HTML解析器的原因,它很慢且可靠。 – AlexanderMP