С Новым годом! Форум программистов, компьютерный форум, киберфорум
PHP для начинающих
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.57/7: Рейтинг темы: голосов - 7, средняя оценка - 4.57
 Аватар для vikusechk
1 / 1 / 0
Регистрация: 16.03.2014
Сообщений: 107

Парсер на php. Настройки cURL

03.03.2016, 08:27. Показов 1513. Ответов 2
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Здравствуйте!
Разрабатываю парсер на php, идея в том, чтобы сделать его более менее универсальным. Т.е. через конфиг передавать настройки по типу: где ищем, что ищем и т.д., а сам процесс парсинга уже будет работать по всем этим настройкам.
Возник вопрос по поводу вытаскивания HTML с помощью cURL. Какие могут потребоваться основные настройки. Пока в голову ничего кроме
PHP
1
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
не приходит. С такой настройкой пока все сайты (их было немного), которые пыталась спрасить, отдали страницу без проблем. Но понимаю, что этого недостаточно для универсальности.

P.S. Я начинающий программист на php, поэтому, если мой вопрос покажется вам тупым, прошу не судить строго)
0
Programming
Эксперт
39485 / 9562 / 3019
Регистрация: 12.04.2006
Сообщений: 41,671
Блог
03.03.2016, 08:27
Ответы с готовыми решениями:

Парсер на PHP с cURL если сайт недоступен
В шапке сайта у меня выводится информация, которая curl'ом берется с другого сайта (назовём его "сайт-донор"). А вчера заметила...

Curl команду превратить в php curl
команда: curl -s -F widget=$WIDGET -F secret=$SECRET -F amouser=$AMOUSER -F amohash=$AMOHASH -F domain=amocrm.ru -F widget=@$file...

Парсер контента на curl
Здравствуйте, написал простенький скрипт получения страницы, но он не работает подскажите почему <?php $url =...

2
Эксперт PHP
3899 / 3237 / 1353
Регистрация: 01.08.2012
Сообщений: 10,904
03.03.2016, 08:41
Да много чего... некоторые сайты могут требовать наличие определённых заголовков (браузер, реферер и т.п.). За отправку заголовков отвечает CURLOPT_HTTPHEADER.

Также может понадобиться сохранение кук:
CURLOPT_COOKIEJAR
CURLOPT_COOKIEFILE

Плюс CURLOPT_FOLLOWLOCATION, если страница устарела и сервер отправил заголовок с редиректом.

Все настройки есть тут. И посмотрите в гугле примеры реализации парсеров, возможно найдёте и другие нужные параметры.
1
Hello Kitty
 Аватар для WhiteMind
690 / 562 / 402
Регистрация: 12.02.2016
Сообщений: 1,436
Записей в блоге: 1
03.03.2016, 13:19
воспользуйтесь примитивным классом .
он маленький но ускоряет работу с курл.
в классе возможны ошибки , но в целом работает
PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
class Common_Misc {
    protected function prepare_name( $name ) {
        return strtolower(trim($name));
    }
}
 
class Cookie_Item {
    public function __construct( $name = null , $value = null , $expire = 0 , $path = null , $domain = null , $secure = false , $httponly = false ) {
        $this->name = $name;
        $this->value = $value;
        $this->expire = $expire;
        $this->path = $path;
        $this->domain = $domain;
        $this->secure = $secure;
        $this->httponly = $httponly;
    }
    public function Serialize() {
        return serialize( (Array) $this );
    }
    public static function Unserialize( $str ) {
        if ( !($a = @unserialize($str)) ) {
            return null;
        }
        $r = new self();
        $r->Change( $a );
        return $r;
    }
    public $name;
    public $value;
    public $expire;
    public $path;
    public $domain;
    public $secure;
    public $httponly;
}
class Cookie_List extends Common_Misc {
    public $change_enabled = true;
    private $cookie_list = [];
    public function Set( Cookie_Item $cookie ) {
        if ( !$this->change_enabled ) { return $this; }
        $name = $cookie->name;
        $name = $this->prepare_name( $name );
        unset($this->cookie_list[ $name ]);
        $this->cookie_list[ $name ] = $cookie;
        return $this;
    }
    public function Get( $name ) {
        $name = $this->prepare_name( $name );
        if ( isset($cookie_list[ $name ]) ) {
            return $cookie_list[ $name ];
        }
        return null;
    }
    public function Has( $name ) {
        $name = $this->prepare_name( $name );
        return isset($cookie_list[ $name ]);
    }
    public function Del( $name ) {
        if ( !$this->change_enabled ) { return $this; }
        $name = $this->prepare_name( $name );
        unset($cookie_list[ $name ]);
        return $this;
    }
    public function Change( $name , $attrKey , $attrVal = null ) {
        if ( !$this->change_enabled ) { return $this; }
        if ( is_array($attrKey) ) {
            foreach($attrKey as $k=>$v) {
                $this->Change( $name , $k , $v );
            }
            return;
        }
        if ( isset($cookie_list[ $name ]) ) {
            $cookie_list[ $name ]->{$attrKey} = $attrVal;
        }
        return $this;
    }
 
    public function ByCurlFile( $path , $clear = true ) {
        if ( !$this->change_enabled ) { return $this; }
        if ( !file_exists($path) )    { return $this; }
 
        if ( $clear ) {
            $this->cookie_list = [];
        }
        $lines = file( $path );
        
        foreach ($lines as $line) {
 
            $cookie = array();
 
            // detect httponly cookies and remove #HttpOnly prefix
            if (substr($line, 0, 10) == '#HttpOnly_') {
                $line = substr($line, 10);
                $cookie['httponly'] = true;
            } else {
                $cookie['httponly'] = false;
            } 
 
            // we only care for valid cookie def lines
            if($line[0] != '#' && substr_count($line, "\t") == 6) {
 
                // get tokens in an array
                $tokens = explode("\t", $line);
 
                // trim the tokens
                $tokens = array_map('trim', $tokens);
 
                // Extract the data
                $cookie['domain'] = $tokens[0]; // The domain that created AND can read the variable.
                $cookie['flag'] = ($tokens[1] !== 'FALSE');   // A TRUE/FALSE value indicating if all machines within a given domain can access the variable. 
                $cookie['path'] = $tokens[2];   // The path within the domain that the variable is valid for.
                $cookie['secure'] = ($tokens[3] !== 'FALSE'); // A TRUE/FALSE value indicating if a secure connection with the domain is needed to access the variable.
 
                $cookie['expire'] = $tokens[4];  // The UNIX time that the variable will expire on.   
                $cookie['name'] = urldecode($tokens[5]);   // The name of the variable.
                $cookie['value'] = urldecode($tokens[6]);  // The value of the variable.
 
                $this->Set(
                    new Cookie_Item($cookie['name'] , $cookie['value'] , $cookie['expire'] , $cookie['path'] , $cookie['domain'] , $cookie['secure'] , $cookie['httponly'])
                );
            }
        }
        return $this;
    }
    public function ToCurlFile( $path ) {
        $s = "";
        $this->Each( function( $cookie ) use( &$s ) {
            $s .= 
                $cookie->domain . "\t" .
                'TRUE' . "\t" .
                $cookie->path . "\t" .
                ($cookie->secure?'TRUE':'FALSE') . "\t" .
                $cookie->expire . "\t" .
                $cookie->name . "\t" .
                $cookie->value . "\r\n";
        } );
        @file_put_contents( $path , $s );
        return $this;
    }
    
    public function Serialize() {
        $a = [];
        foreach($this->cookie_list as $c) {
            $a[] = $c->Serialize();
        }
        return serialize( $a );
    }
    public static function Unserialize( $str ) {
        if ( !($a = @unserialize($str)) ) {
            return null;
        }
        $r = new self();
        foreach($a as $c) {
            $r->Set( Cookie_Item::Unserialize( $c ) );
        }
        return $r;
    }
 
    public function Each( $f ) {
        foreach($this->cookie_list as $c) {
            $f( $c );
        }
        return $this;
    }
}
class Header {
    public $name;
    public $values;
    public function __construct( $name , $values ) {
        if ( !is_array($values) ) {
            $values = [$values];
        }
        $this->name = trim($name);
        foreach($values as &$v) {
            $v = trim($v);
        }
        $this->values = $values;
    }
    public function Add( $value ) {
        $this->values[] = trim($value);
    }
    public function ToString() {
        $result = "";
        foreach($this->values as $val) {
            $result .= trim( trim($this->name) . ": " . $this->prepare_value($val) ) . "\r\n";
        }
        return trim($result);
    }
    private function prepare_value( $value ) {
        return trim(str_replace( "\r\n" , "\r\n " , $value ));
    }
}
class Headers extends Common_Misc {
    public $head;
    public $headers = [];
    public function Set( Header $header ) {
        $this->headers[ $this->prepare_name( $header->name ) ] = $header;
        return $this;
    }
    public function Add( $name , $value ) {
        if ( $h = $this->Get( $name ) ) {
            $h->Add($value);
        } else {
            $this->Set( new Header( $name , $value ) );
        }
    }
    public function Get( $name ) {
        if ( isset($this->headers[ $name = $this->prepare_name( $name ) ]) ) {
            return $this->headers[ $name ];
        }
        return null;
    }
    public function Has( $name ) {
        return isset($this->headers[ $name = $this->prepare_name( $name ) ]);
    }
    public function Del( $name , $index = null ) {
        if  ( $index === null ) {
            unset( $this->headers[ $name = $this->prepare_name( $header->name ) ] );
        } elseif ( $h = $this->Get( $name ) ) {
            array_splice($h->values , $index , 1);
        }
        return $this;
    }
    public function ToString( $use_head = true ) {
        $result = "";
        if ( $this->head && $use_head ) {
            $result = $this->head . "\r\n";
        }
        $this->Each( function( $header ) use (&$result) {
            $result .= $header->ToString() . "\r\n";
        } );
        return $result;
    }
    public static function ByString( &$string ) {
        $_this = new self();
        if ( ($pos = strpos( $string , "\r\n\r\n" )) === false ) {
            return $_this;
        }
        $headers_string = substr($string , 0 , $pos + 2);
        $string = substr($string , $pos+4);
 
        do {
            $rand_s = substr(str_shuffle( "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM0123456789" ) , 0 , 32);
        } while( strpos($headers_string , $rand_s) !== false );
        
        $headers_string = str_replace( "\r\n " , $rand_s , $headers_string );
        $headers_string = str_replace( "\r\n\x09" , $rand_s , $headers_string );
        preg_match( "#([^\r\n:]*)\r\n#si" , $headers_string , $res );
        if ( !@$res[1] ) {
            return;
        }
        $_this->head = "";
        if ( strpos($res[1] , ":") !== false ) {
            $_this->head = trim( str_replace( $rand_s , "\r\n" , $res[1] ) );
        }
        
        preg_match_all( "#([^\r\n:]*):([^\r\n]*)\r\n#si" , $headers_string , $res );
        foreach($res[1] as $i=>$v) {
            $name = trim( str_replace( $rand_s , "\r\n" , $res[1][$i] ) );
            $value = trim( str_replace( $rand_s , "\r\n" , $res[2][$i] ) );
            $_this->Add( $name , $value );
        }
        return $_this;
    }
    public function Each( $f ) {
        foreach($this->headers as $header) {
            $f( $header );
        }
        return $this;
    }
    public function GetCurlArray() {
        $result = [];
        $this->Each( function( $header ) use (&$result) {
            $result[] = trim($header->ToString());
        } );
        return $result;
    }
 
    public function __construct() {
        foreach( func_get_args() as $arg ) {
            if ( !is_array($arg) ) {
                $arg = [$arg];
            }
            foreach($arg as $v) {
                $this->Set($v);
            }
        }
    }
}
class Curl_Return {
    public $error;
    public $info;
    public $headers;
    public $request_headers;
    public $content;
    public function __construct( $error , $content , $info ) {
        $this->error   = $error;
        $this->content = $content;
        $this->info    = $info;
        $this->headers = Headers::ByString( $this->content );
        $this->request_headers = Headers::ByString( $this->info['request_header'] );
    }
}
class Curl {
    public static function Get( $info = [] , Headers $headers = null , Cookie_List $cookie = null ) {
        $info = (Array)$info;
        $info["method"] = "get";
        return new self( $info , $headers , $cookie );
    }
    public static function Post( $info = [] , Headers $headers = null , Cookie_List $cookie = null ) {
        $info = (Array)$info;
        $info["method"] = "post";
        return new self( $info , $headers , $cookie );
    }
 
    private $curl;
    private $curl_multi;
    private $curl_active;
    
    public $url;
    public $useragent = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.116 Safari/537.36';
    public $timeout = 10;
    public $connecttimeout = 3;
    public $method = 'get';
    public $fresh_connect = true;
    public $forbid_reuse = true;
    public $parameters = [];
 
    public $cookie_tmp_dir = "MTGNHQDDNPYLMMIWFYNQOYBNWEWHQSLV";
    private $cookie_tmp_file;
 
    private $attr_map = [ 
        'url' => CURLOPT_URL , 
        'useragent' => CURLOPT_USERAGENT , 
        'timeout' => CURLOPT_TIMEOUT , 
        'connecttimeout' => CURLOPT_CONNECTTIMEOUT ,
        'fresh_connect' => CURLOPT_FRESH_CONNECT ,
        'forbid_reuse' => CURLOPT_FORBID_REUSE
    ];
    public function __construct( $info = [] , Headers $headers = null , Cookie_List $cookie = null ) {
        if ( !is_dir( $this->cookie_tmp_dir ) ) {
            @mkdir($this->cookie_tmp_dir);
        }
 
        if ( $cookie === null  ) { $cookie = new Cookie_List(); }
        if ( $headers === null ) { $headers = new Headers(); }
        $this->cookie = $cookie;
        $this->headers = $headers;
        
        $this->Change( $info );
        return $this;
    }
    public function Change( $info = [] , $value2 = null ) {
        if ( $value2 !== null ) {
            $info = [ $info => $value2 ];
        }
        $info = (Array)$info;
        foreach($info as $k=>$v) {
            $this->{$k} = $v;
        }   
    }
 
    public function Load( $url = null ) {   
        $this->startLoad();
 
        if ( $url !== null ) {
            $this->url = $url;
        }
    
        $isPost = (strtolower(trim($this->method)) === "post");
 
        $options = Array(
            CURLOPT_POST => $isPost,
 
            CURLOPT_HEADER => 1, 
            CURLOPT_RETURNTRANSFER => 1,
            CURLINFO_HEADER_OUT => 1,
            CURLOPT_COOKIEFILE => $this->cookie_tmp_file,
            CURLOPT_COOKIEJAR => $this->cookie_tmp_file,
            CURLOPT_SSL_VERIFYPEER => 0
        );
        
        foreach($this->attr_map as $k=>$v) {
            $options[ $v ] = $this->{$k};
        }
        
        if ( $isPost ) {
            $options[ CURLOPT_POSTFIELDS ] = $this->parameters;
        }
 
        $options[ CURLOPT_HTTPHEADER ] = $this->headers->GetCurlArray();
        
        $this->curl_active = null;
        
        $this->curl = @curl_init();
        @curl_setopt_array( $this->curl , $options );
 
        $this->curl_multi = @curl_multi_init();
 
        @curl_multi_add_handle( $this->curl_multi , $this->curl );
        
        $this->IsLoad();
 
        return $this;
    }
    public function IsLoad() {
        $status = @curl_multi_exec( $this->curl_multi , $this->curl_active );
        $result = !($status === CURLM_CALL_MULTI_PERFORM || $this->curl_active);
        if ( $result ) {
            $this->result = new Curl_Return( @curl_error( $this->curl ) , @curl_multi_getcontent( $this->curl ) , @curl_getinfo( $this->curl ) );
            @curl_multi_remove_handle($this->curl_multi , $this->curl);
            @curl_close($this->curl);
            @curl_multi_close($this->curl_multi);
            $this->endLoad();
        }
        return $result;
    }
    public function Wait() {
        while( !$this->IsLoad() ) {
            usleep( $this->wait_time );
        }
        return $this;
    }
    private $wait_time = 100000;
    
    public $result;
    public $cookie;
    public $headers;
    
    
    private function startLoad() {
        $this->result = null;
        $this->cookie_tmp_file = tempnam($this->cookie_tmp_dir , "tmp");
        $this->cookie->ToCurlFile( $this->cookie_tmp_file );
    }
    private function endLoad() {
        $this->cookie->ByCurlFile( $this->cookie_tmp_file );
        unlink($this->cookie_tmp_file);
    }
}
1
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
inter-admin
Эксперт
29715 / 6470 / 2152
Регистрация: 06.03.2009
Сообщений: 28,500
Блог
03.03.2016, 13:19
Помогаю со студенческими работами здесь

Парсер с использованием CURL
Здравствуйте, столкнулся с вопросом. Пытаюсь парсить сайт с помощью CURL. Вот так описываю подключение: $matches = array(); ...

Парсер на CURL. Пустой запрос от сервера
Здравствуйте. Помогите, пожалуйста, решить такую проблему. Есть парсер, данные получает при помощи CURL. Обрабатывает 39 запросов нормально...

Парсер на curl: найти все ссылки на странице
Всем привет. Столкнулась с проблемой написания парсера. Что нужно. Получить страницу, это получилось, теперь нужно найти все ссылки...

Парсер на CURL и ошибка Network Error (tcp_error)
Здравствуйте. Пишу парсер, данные получаются через CURL. Когда запускаю на локальном компьютере - всё хорошо работает, все данные...

Как преобразовать обычный CURL парсер в многопоточный
Есть парсер который использует библиотеки CURL и phpQuery. Он парсит данные с с сайта и сохраняет всё с .csv файл. Но проблема в том, что...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
3
Ответ Создать тему
Новые блоги и статьи
Советы по крайней бережливости. Внимание, это ОЧЕНЬ длинный пост.
Programma_Boinc 28.12.2025
Советы по крайней бережливости. Внимание, это ОЧЕНЬ длинный пост. Налог на собак: https:/ / **********/ gallery/ V06K53e Финансовый отчет в Excel: https:/ / **********/ gallery/ bKBkQFf Пост отсюда. . .
Кто-нибудь знает, где можно бесплатно получить настольный компьютер или ноутбук? США.
Programma_Boinc 26.12.2025
Нашел на реддите интересную статью под названием Anyone know where to get a free Desktop or Laptop? Ниже её машинный перевод. После долгих разбирательств я наконец-то вернула себе. . .
Thinkpad X220 Tablet — это лучший бюджетный ноутбук для учёбы, точка.
Programma_Boinc 23.12.2025
Рецензия / Мнение/ Перевод Нашел на реддите интересную статью под названием The Thinkpad X220 Tablet is the best budget school laptop period . Ниже её машинный перевод. Thinkpad X220 Tablet —. . .
PhpStorm 2025.3: WSL Terminal всегда стартует в ~
and_y87 14.12.2025
PhpStorm 2025. 3: WSL Terminal всегда стартует в ~ (home), игнорируя директорию проекта Симптом: После обновления до PhpStorm 2025. 3 встроенный терминал WSL открывается в домашней директории. . .
Как объединить две одинаковые БД Access с разными данными
VikBal 11.12.2025
Помогите пожалуйста !! Как объединить 2 одинаковые БД Access с разными данными.
Новый ноутбук
volvo 07.12.2025
Всем привет. По скидке в "черную пятницу" взял себе новый ноутбук Lenovo ThinkBook 16 G7 на Амазоне: Ryzen 5 7533HS 64 Gb DDR5 1Tb NVMe 16" Full HD Display Win11 Pro
Музыка, написанная Искусственным Интеллектом
volvo 04.12.2025
Всем привет. Некоторое время назад меня заинтересовало, что уже умеет ИИ в плане написания музыки для песен, и, собственно, исполнения этих самых песен. Стихов у нас много, уже вышли 4 книги, еще 3. . .
От async/await к виртуальным потокам в Python
IndentationError 23.11.2025
Армин Ронахер поставил под сомнение async/ await. Создатель Flask заявляет: цветные функции - провал, виртуальные потоки - решение. Не threading-динозавры, а новое поколение лёгких потоков. Откат?. . .
Поиск "дружественных имён" СОМ портов
Argus19 22.11.2025
Поиск "дружественных имён" СОМ портов На странице: https:/ / norseev. ru/ 2018/ 01/ 04/ comportlist_windows/ нашёл схожую тему. Там приведён код на С++, который показывает только имена СОМ портов, типа,. . .
Сколько Государство потратило денег на меня, обеспечивая инсулином.
Programma_Boinc 20.11.2025
Сколько Государство потратило денег на меня, обеспечивая инсулином. Вот решила сделать интересный приблизительный подсчет, сколько государство потратило на меня денег на покупку инсулинов. . . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2025, CyberForum.ru