Парсер Vkontakte.ru

Написано 12:41, ярлыки:

$user_agent = 'Mozilla/5.0 (Windows; U; Windows NT 6.0; ru; rv:1.9.2.13) ' . 
             'Gecko/20101203 Firefox/3.6.13 ( .NET CLR 3.5.30729)';

$cookie = '';

$login = 'qazqaz';
$password = 'qazqaz';

$ch = curl_init();

// true т.к. мы будем отправлять post запрос:
curl_setopt($ch, CURLOPT_POST, true);  

// чтобы сайт думал, что мы - браузер:
curl_setopt($ch, CURLOPT_USERAGENT, $user_agent); 

// ответ сервера будем записывать в переменную
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 

curl_setopt($ch, CURLOPT_TIMEOUT, 10);

// по редиректам будем переходить автоматически.
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

curl_setopt($ch, CURLOPT_URL, 'http://login.vk.com/?act=login');

//Формирование запроса таким образом, я счел более наглядным
$post = array( 
             'act' => 'login',
             'q' => '',
             'al_frame' => '1',
             'expire' => '',
             'captcha_sid' => '',
             'captcha_key' => '',
             'from_host' => 'vkontakte.ru',
             'email' => $login,
             'pass' => $password
         );

curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));

$answer = curl_exec($ch);

/* В $answer нам приходит javascript, который и устанавливает куки 
     с названием: remixsid Нам нужно cпарсить эти 60 символов, 
     идентификатора сессии. с помощью них vkontakte поймет,
     что мы авторизировались.*/

$sid = substr($answer, strpos($answer, "setCookieEx('sid', '") + 20, 60);
$cookie = 'remixsid=' . $sid;

curl_setopt($ch, CURLOPT_POST, false);
curl_setopt($ch, CURLOPT_COOKIE, $cookie); 

// укажем страницу, с которой мы получим данные для проверки
curl_setopt($ch, CURLOPT_URL, 'http://vkontakte.ru/id107073034'); 

$answer = curl_exec($ch);

preg_match('!id="profile_current_info">((.*?))</div>!si',$answer,$data);
//print_r($data);

$pars=iconv('cp1251','utf-8',$data[1]);
//echo $pars;

$p = file_get_contents('/home/megido/l.dat');
if($p != $pars)

$f = @fopen('/home/qazqaz/l.dat','w+');
fwrite($f,$pars);
fclose($f);





//echo $answer; 

curl_close($ch);





edit post
$cnt=100; // общее количество записей во всём выводе
$rpp=10; // кол-во записей на страницу
$rad=1; // сколько ссылок показывать рядом с номером текущей страницы (2 слева + 2 справа + активная страница = всего 5)
$link_sc='page_navigation.php'; // путь
if (isset($_GET['page']))
{
  $page=$_GET['page']-1; // текущая страница
}
else
{
  $page=0;
}
 
$links=$rad*2+1;
$pages=ceil($cnt/$rpp);
if ($page>0) { echo "First | Previous |"; }
$start=$page-$rad;
if ($start>$pages-$links) { $start=$pages-$links; }
if ($start<0) { $start=0; }
$end=$start+$links;
if ($end>$pages) { $end=$pages; }
for ($i=$start; $i<$end; $i++) {
 echo " ";
 
 if ($i==$page) {
  echo "";
 } else {
  echo "";
 }
// echo ($i*$rpp+1)."-";
// if ($i!=($pages-1)) { echo $i*$rpp+$rpp; } else { echo $cnt; }
 echo ($i+1);
 if ($i==$page) {
  echo "";
 } else {
  echo "";
 }
 if ($i!=($end-1)) { echo " |"; }
}
if ($pages>$links&&$page<($pages-$rad-1)) { echo " ... ".($pages).""; }
if ($page<$pages-1) { echo " Next | Last"; }

edit post
для начала создадим скрипт
var d = document;
var offsetfromcursorY=15 // y offset of tooltip
var ie=d.all && !window.opera;
var ns6=d.getElementById && !d.all;
var tipobj,op;
  
function tooltip(el,txt) {
 tipobj=d.getElementById('mess');
 tipobj.innerHTML = txt;
 op = 0.1; 
 tipobj.style.opacity = op; 
 tipobj.style.visibility="visible";
 el.onmousemove=positiontip;
 appear();
}

function hide_info(el) {
 d.getElementById('mess').style.visibility='hidden';
 el.onmousemove='';
}

function ietruebody(){
return (d.compatMode && d.compatMode!="BackCompat")? d.documentElement : d.body
}

function positiontip(e) {
 var curX=(ns6)?e.pageX : event.clientX+ietruebody().scrollLeft;
 var curY=(ns6)?e.pageY : event.clientY+ietruebody().scrollTop;
 var winwidth=ie? ietruebody().clientWidth : window.innerWidth-20
 var winheight=ie? ietruebody().clientHeight : window.innerHeight-20
 
 var rightedge=ie? winwidth-event.clientX : winwidth-e.clientX;
 var bottomedge=ie? winheight-event.clientY-offsetfromcursorY : winheight-e.clientY-offsetfromcursorY;

 if (rightedge < tipobj.offsetWidth) tipobj.style.left=curX-tipobj.offsetWidth+"px";
 else tipobj.style.left=curX+"px";

 if (bottomedge < tipobj.offsetHeight) tipobj.style.top=curY-tipobj.offsetHeight-offsetfromcursorY+"px"
 else tipobj.style.top=curY+offsetfromcursorY+"px";
}

function appear() { 
 if(op < 1) {
  op += 0.1;
  tipobj.style.opacity = op;
  tipobj.style.filter = 'alpha(opacity='+op*100+')';
  t = setTimeout('appear()', 30);
 }
}
затем проинклюдим его и вставим в тело html div в каком будут отображатся подсказки

<div  Style="visibility: hidden; position: absolute" id="mess">





</div>
осталось толко заключить наш текст или картинку или еще чего

над этим текстом подсказка

Пример:

над этим текстом подсказка


* на блоггере она почему то ниже чем нужно

edit post
для подсветки самое лучшее решение бедет скрипты гугла

для этого открывам редактирование шаблона
как показано на рисунке


(для каждой темы придется редактировать шаблон отдельно)



и добавляем после тега <head>
следующий код:




<link href="//google-code-prettify.googlecode.com/svn/trunk/src/prettify.css" rel="stylesheet" type="text/css">
<script src="//google-code-prettify.googlecode.com/svn/trunk/src/prettify.js" type="text/javascript">  </script>

ну и дополнив тег body добавив в него это:


onload='prettyPrint()'
на этом настройка заканчивается, для подсветки кода нужно просто заключить его в тег

<pre class="prettyprint">код
</pre>

edit post
#!/usr/bin/env python
from PIL import Image, ImageDraw, ImageFont
import datetime
import time
from random import randint
import os

def hash(mode=0):
 x=''
 letters=['A', 'a', 'B', 'b', 'C', 'c', 'D', 'd', 'E'
, 'e', 'F', 'f', 'G', 'g', 'H', 'h', 'I', 'i',
 'J', 'j', 'K', 'k', 'L', 'l', 'M', 'm', 'N', 'nO',
  'o', 'P', 'p', 'Q', 'R', 'r', 'S', 's', 'T', 't', 
  'U', 'u', 'V', 'W', 'w', 'X', 'x', 'Y', 'y', 'Z', 'z']
 numbers = [1,2,3,4,5,6,7,8,9,0]
 a = [letters,numbers]
 if mode == 0:
  two=randint(20,33)
 else:
  two = 10
  
 for i in range(0,two):
  ii = randint(0,1)
  array=a[ii]
  letter=array[randint(0,len(array)-1)]
  x = str(x)+str(letter)
 return x

def ru(x):
# return(x.decode('utf-8'))
    unicode(x,'utf-8')
def main(img=None,header=None,descr=None,bg=None,mode=None):
    if img == None or header == None or descr == None or bg == None:
        print "demotivator.py imagefile header description [bg_color]"
        print "\tExample: python demotivator.py image.png 'Demotivator' 'This is demotivator'"
        exit(0)

    file =img     
    TOP_BORDER=40
    BOTTOM_BORDER=20
    LEFT_BORDER=40
    RIGHT_BORDER=40
    BIG_FONT_SIZE=48
    SMALL_FONT_SIZE=16
    BG_COLOR="#010101"
    BG_COLOR=bg
     
    # Loading fonts
    big_font = ImageFont.truetype("/usr/share/fonts/droid/DroidSansFallback.ttf",
                                  BIG_FONT_SIZE, encoding="unic")
    header = header
    big_font_size = big_font.getsize(header)
    small_font = ImageFont.truetype("/usr/share/fonts/droid/DroidSansFallback.ttf",
                                    SMALL_FONT_SIZE, encoding="unic")
    descr = descr
    small_font_size = small_font.getsize(descr)
     
    # Calculating size of demotivator
    src_img = Image.open(img)
    src_size = src_img.getbbox()[2:]
    dst_size = list(src_size)
    dst_size[0] += LEFT_BORDER + RIGHT_BORDER
    dst_size[1] += TOP_BORDER + BOTTOM_BORDER + \
        big_font_size[1] + small_font_size[1] + 5
     
    # Making border
    dst_img = Image.new("RGB", dst_size, "black")
    dst_draw = ImageDraw.Draw(dst_img)
    dst_draw.rectangle([0, 0, dst_size[0], dst_size[1]], fill=BG_COLOR)
    dst_img.paste(src_img, (LEFT_BORDER, TOP_BORDER))
     
    # Drawing border lines
    dst_draw.line(
        (LEFT_BORDER - 3, TOP_BORDER - 3,
         dst_size[0] - RIGHT_BORDER + 3, TOP_BORDER - 3),
        width=1)
    dst_draw.line(
        (dst_size[0] - RIGHT_BORDER + 3, TOP_BORDER - 3,
         dst_size[0] - RIGHT_BORDER + 3, TOP_BORDER + src_size[1] + 3),
        width=1)
    dst_draw.line(
        (LEFT_BORDER - 3, TOP_BORDER + src_size[1] + 3,
         dst_size[0] - RIGHT_BORDER + 3, TOP_BORDER + src_size[1] + 3),
        width=1)
    dst_draw.line(
        (LEFT_BORDER - 3, TOP_BORDER + src_size[1] + 3,
         LEFT_BORDER - 3, TOP_BORDER - 3),
        width=1)
     
    # Drawing text
    text_pos_x = (dst_size[0] - big_font_size[0]) / 2
    text_pos_y = src_img.getbbox()[3] + TOP_BORDER + 5
    dst_draw.text((text_pos_x, text_pos_y), header, font=big_font)
    text_pos_x = (dst_size[0] - small_font_size[0]) / 2
    text_pos_y += big_font_size[1] + 5
    dst_draw.text((text_pos_x, text_pos_y), descr, font=small_font)
     
    # Saving and showing image
    dt = datetime.datetime.now()
    date=time.mktime(dt.timetuple())
       

    n= '/var/www/'
    
    name = str(hash())+'-'+str(date)+'.png'
    dst_img.save(n+name, "PNG")

    img = Image.open(n+name)
    img.thumbnail((350, 400), Image.ANTIALIAS)
    img.save(n+'2-'+name,"PNG")

edit post
для масштабирования используют PIL

from PIL import Image
img = Image.open(name) # открываем изображение
img.thumbnail((320, 450), Image.ANTIALIAS) # изменяем пропорции
img.save(name,"PNG") # сохраняем

edit post