Lấy dữ liệu tự động

Website

Các bước lấy dữ liệu tự động từ website khác.

Khai báo thư viện

$soc->use_html();

Lấy dữ liệu của một URL bất kỳ

// Lấy dữ liệu của $url theo giao thức get ($curl=0), hoặc giao thức post ($curl=1) với $post là mảng dữ liệu được gửi đi
$soc->html->get_source($url, $curl=0, $post=array());

Chuyển HTML sang DOM

Mặc định, dữ liệu lấy được từ một trang web sẽ là chuỗi HTML. Để bóc tách dữ liệu trong chuỗi này cần cần chuyển sang DOM (kiểu cấu trúc cây) sử dụng hàm sau:

// Chuyển chuỗi $html sang DOM ($html là dữ liệu lấy được từ hàm get_source)
$soc->html->to_dom($html);

Lấy DOM của một URL bất kỳ

// Hàm kết hợp của hàm get_source và hàm to_dom
$soc->html->get_dom($url, $curl=0, $post=array());

Ví dụ để hiểu rõ hơn


// Lấy source HTML dưới dạng chuỗi
$source = $soc->html->get_source('https://thietkewebso.com', 1);
if($source){ // Nếu get được dữ liệu
	// Chuyển từ chuỗi sang dạng DOM
	$dom = $soc->html->to_dom($source);
	if($dom){ // Chuyển sang DOM thành công
		
		// Lấy ra thẻ img đầu tiên và in ra src
		$first_img = $dom->find('img', 0);
		if($first_img){
			echo $first_img->src;
		}
		
		// Lấy ra tất cả thẻ a và in ra href
		foreach($dom->find('a') as $a){
			echo $a->href;
		}
		
		// Bỏ script, style trong $source
		foreach($dom->find('script,style') as $script){
			$script->outertext = '';
		}
		
		// Chỉnh lại nội dung bên trong thẻ p thứ 2 thành abc
		$second_p = $dom->find('p', 1);
		if($second_p){
			$second_p->innertext = 'abc';
		}
		
		// In ra text bên trong div có class="xyz" đầu tiên
		$div_xyz = $dom->find('div.xyz', 0);
		if($div_xyz){
			echo $div_xyz->plaintext;
		}
		
		// In ra tất cả thẻ a bên trong id="tn"
		foreach($dom->find('#tn a') as $a){
			echo $a; // hoặc echo $a->outertext;
		}
		
		// In ra tất cả thẻ a có rel="nofollow"
		foreach($dom->find('a[rel="nofollow"]') as $a){
			echo $a; // hoặc echo $a->outertext;
		}
		
		// Ẩn mọi thẻ pre và thêm alt cho tất cả thẻ img
		foreach($dom->find('pre,img') as $x){
			if($x->tag=='pre'){
				$x->outertext = '<div style="display:none">'.$x->outertext.'</div>';
			}else{
				$x->alt = 'Chú tích cho ảnh';
			}
		}
		
		// Tìm ra div con đầu tiên bên trong div class="social"
		$first_social = $dom->find('.social', 0);
		if($first_social){
			$first_social->first_child(); // Tìm cha con anh em: parent / children / first_child / last_child / next_sibling / prev_sibling
		}
		
	}
}


Dustin Nelson

Gia nhập: 27-01-2016 Dustin Nelson

Chuyên thiết kế mọi loại website.