php如何实现在web中,如何在PHP中实现Web scraper?

063b71e2dbc4be2b49c6eddcd4ce994d.png

慕桂英4014372

刮痧通常包括3个步骤:首先,您将请求获取或发送到指定的URL接下来,您将收到作为响应返回的html最后你解析那个html你要抓的文字。要完成步骤1和2,下面是一个简单的php类,它使用Curl来使用GET或POST获取网页。在您获得HTML之后,您只需使用正则表达式通过解析您要删除的文本来完成步骤3。对于正则表达式,我最喜欢的教程网站如下: 正则表达式教程我最喜欢使用RegExs的程序是Regex Buddy。即使您无意购买,我也会建议您尝试该产品的演示。它是一个非常宝贵的工具,甚至可以为您使用您选择的语言(包括php)制作的正则表达式生成代码。用法:$curl = new Curl();$html = $curl->get("http://www.google.com");// now, do your regex work against $htmlPHP类:<?phpclass  Curl{       

    public $cookieJar = "";

    public function __construct($cookieJarFile = 'cookies.txt') {

        $this->cookieJar = $cookieJarFile;

    }

    function setup()

    {

        $header = array();

        $header[0] = "Accept: text/xml,application/xml,application/xhtml+xml,";

        $header[0] .= "text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";

        $header[] =  "Cache-Control: max-age=0";

        $header[] =  "Connection: keep-alive";

        $header[] = "Keep-Alive: 300";

        $header[] = "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7";

        $header[] = "Accept-Language: en-us,en;q=0.5";

        $header[] = "Pragma: "; // browsers keep this blank.

        curl_setopt($this->curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US; rv:1.8.1.7) Gecko/20070914 Firefox/2.0.0.7');

        curl_setopt($this->curl, CURLOPT_HTTPHEADER, $header);

        curl_setopt($this->curl,CURLOPT_COOKIEJAR, $this->cookieJar); 

        curl_setopt($this->curl,CURLOPT_COOKIEFILE, $this->cookieJar);

        curl_setopt($this->curl,CURLOPT_AUTOREFERER, true);

        curl_setopt($this->curl,CURLOPT_FOLLOWLOCATION, true);

        curl_setopt($this->curl,CURLOPT_RETURNTRANSFER, true);  

    }

    function get($url)

    { 

        $this->curl = curl_init($url);

        $this->setup();

        return $this->request();

    }

    function getAll($reg,$str)

    {

        preg_match_all($reg,$str,$matches);

        return $matches[1];

    }

    function postForm($url, $fields, $referer='')

    {

        $this->curl = curl_init($url);

        $this->setup();

        curl_setopt($this->curl, CURLOPT_URL, $url);

        curl_setopt($this->curl, CURLOPT_POST, 1);

        curl_setopt($this->curl, CURLOPT_REFERER, $referer);

        curl_setopt($this->curl, CURLOPT_POSTFIELDS, $fields);

        return $this->request();

    }

    function getInfo($info)

    {

        $info = ($info == 'lasturl') ? curl_getinfo($this->curl, CURLINFO_EFFECTIVE_URL) : curl_getinfo($this->curl, $info);

        return $info;

    }

    function request()

    {

        return curl_exec($this->curl);

    }}?>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值