PHP抓取网络数据的6种常见方法

本小节的名称为 fsockopen,curl与file_get_contents,具体是探讨这三种方式进行网络数据输入输出的一些汇总。这里先简单罗列一下一些常见的抓取网络数据的一些方法。

1. 用 file_get_contents 以 get 方式获取内容:

// $url = ‘https://www.ztmbz.com’;

$url = ‘https://www.ztmbz.com/php/sock.php’;

$html = file_get_contents($url);

echo $html;

2. 用fopen打开url,以get方式获取内容

// $url = ‘http://www.nowamagic.net’;

$url = ‘http://www.nowamagic.net/php/sock.php’;

$fp = fopen($url, ‘r’);

stream_get_meta_data($fp);

$result = ”;

while(!feof($fp))

{

$result .= fgets($fp, 1024);

}

echo “url body: $result”;

fclose($fp);

3. 用file_get_contents函数,以post方式获取url

$data = array(

‘foo’=>’bar’,

‘baz’=>’boom’,

‘site’=>’www.nowamagic.net’,

‘name’=>’nowa magic’);

$data = http_build_query($data);

//$postdata = http_build_query($data);

$options = array(

‘http’ => array(

‘method’ => ‘POST’,

‘header’ => ‘Content-type:application/x-www-form-urlencoded’,

‘content’ => $data

//’timeout’ => 60 * 60 // 超时时间(单位:s)

)

);

$url = “http://www.nowamagic.net/test2.php”;

$context = stream_context_create($options);

$result = file_get_contents($url, false, $context);

echo $result;

4. 用 fsockopen 函数打开url,以get方式获取完整的数据,包括header和body

// $url = ‘https://www.ztmbz.com’;

$url = ‘https://www.ztmbz.com:80/php/sock.php?site=xiaoerhu.com’;

function get_url($url,$cookie=false)

{

$url = parse_url($url);

$query = $url[‘path’].”?”.$url[‘query’];

echo “Query:”.$query;

$fp = fsockopen( $url[‘host’], $url[‘port’]?$url[‘port’]:80 , $errno, $errstr, 30);

if (!$fp)

{

return false;

}

else {

$request = “GET $query HTTP/1.1\r\n”;

$request .= “Host: $url[host]\r\n”;

$request .= “Connection: Close\r\n”;

if($cookie) $request.=”Cookie: $cookie\n”;

$request.=”\r\n”;

fwrite($fp,$request);

$result = ”;

while(!feof($fp))

{

$result .= @fgets($fp, 1024);

}

fclose($fp);

return $result;

}

}

//获取url的html部分,去掉header

function GetUrlHTML($url,$cookie=false)

{

$rowdata = get_url($url,$cookie);

if($rowdata)

{

$body= stristr($rowdata,”\r\n\r\n”);

$body=substr($body,4,strlen($body));

return $body;

}

return false;

}

echo get_url($url);

echo GetUrlHTML($url);

5. 用fsockopen函数打开url,以POST方式获取完整的数据,包括header和body

// $url = ‘https://www.ztmbz.com’;

$url = ‘https://www.ztmbz.com:80/php/sock.php?site=xiaoerhu.com’;

function HTTP_Post($URL,$data,$cookie, $referer=””)

{

// parsing the given URL

$URL_Info=parse_url($URL);

// Building referrer

if($referer==””) // if not given use this script as referrer

$referer=“www.ztmbz.com”;

// making string from $data

foreach($data as $key=> $value)

$values[]=”$key=”.urlencode($value);

$data_string=implode(“&”,$values);

// Find out which port is needed – if not given use standard (=80)

if(!isset($URL_Info[“port”]))

$URL_Info[“port”]=80;

$request = ”;

// building POST-request:

$request.=”POST “.$URL_Info[“path”].” HTTP/1.1\n”;

$request.=”Host: “.$URL_Info[“host”].”\n”;

$request.=”Referer: $referer\n”;

$request.=”Content-type: application/x-www-form-urlencoded\n”;

$request.=”Content-length: “.strlen($data_string).”\n”;

$request.=”Connection: close\n”;

$request.=”Cookie: $cookie\n”;

$request.=”\n”;

$request.=$data_string.”\n”;

$fp = fsockopen($URL_Info[“host”],$URL_Info[“port”]);

fputs($fp, $request);

$result = ”;

while(!feof($fp))

{

$result .= fgets($fp, 1024);

}

fclose($fp);

return $result;

}

$data = array(

‘foo’=>’bar’,

‘baz’=>’boom’,

‘site’=>’www.ztmbz.com’,

‘name’=>’nowa magic’);

$cookie = ”;

$referer = ‘https://www.ztmbz.com’;

echo HTTP_Post($url, $data, $cookie, $referer);

6. 使用curl库,使用curl库之前,可能需要查看一下php.ini是否已经打开了curl扩展。

使用 curl 代码比较简洁,代码也比较规范,容易理解:

// $url = ‘https://www.ztmbz.com’;

$url = ‘https://www.ztmbz.com:80/php/sock.php?site=xiaoerhu.com’;

$ch = curl_init();

$timeout = 5;

curl_setopt ($ch, CURLOPT_URL, $url);

curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);

curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);

$file_contents = curl_exec($ch);

curl_close($ch);

echo $file_contents;

这里就大概列举这么 6 种抓取网络数据的方式,也是比较常见的,让大家先有个总体的理解,还有各方法的比较。

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
### 回答1: VBA(Visual Basic for Applications)是一宏语言,可以通过编写代码来实现自动化任务。使用VBA抓取网页数据方法可以通过以下步骤来完成: 1. 创建一个Excel文件,并在工作表中打开"开发者工具"选项卡。 2. 在"开发者工具"选项卡中,点击"Visual Basic"按钮,打开VBA编辑器。 3. 在VBA编辑器中,选择"插入",然后选择"模块",创建一个新的模块。 4. 在新的模块中,编写VBA代码来实现抓取网页数据的功能。以下是一个简单的示例代码: Sub GetDataFromWebsite() Dim ie As InternetExplorer Dim doc As HTMLDocument Dim table As Object Dim i As Integer '创建一个Internet Explorer对象 Set ie = CreateObject("InternetExplorer.Application") '打开一个网页 ie.Visible = True ie.navigate "http://www.example.com" '等待网页加载完成 Do While ie.readyState <> READYSTATE_COMPLETE DoEvents Loop '将网页内容存储在一个HTMLDocument对象中 Set doc = ie.document '找到网页中的表格 Set table = doc.getElementsByTagName("table")(0) '遍历表格的行和列,并将数据输出到Excel工作表中 i = 1 For Each row In table.Rows For Each cell In row.Cells Worksheets("Sheet1").Cells(i, 1).Value = cell.innerText i = i + 1 Next cell Next row '关闭Internet Explorer对象 ie.Quit End Sub 以上代码中,我们首先创建一个InternetExplorer对象,然后使用该对象来打开指定的网页。在网页加载完成后,我们通过HTMLDocument对象来获取网页内容,并使用getElementsByTagName方法找到需要抓取的表格。最后,我们可以使用循环遍历表格的行和列,并将数据输出到Excel工作表中。 总结来说,使用VBA抓取网页数据方法包括使用InternetExplorer对象来打开网页,使用HTMLDocument对象来获取网页内容,然后解析网页获取所需数据,并将数据输出到Excel或其他文件中。这样就可以实现自动化抓取网页数据的功能。 ### 回答2: VBA(Visual Basic for Applications)是一用于编写宏和自动化任务的编程语言,可以通过它来实现抓取网页数据的功能。 在VBA中,我们可以使用Internet Explorer对象来模拟浏览器,访问网页并获取数据。以下是一常见抓取网页数据方法: 1. 创建一个新的VBA模块,并在其中添加以下代码: ``` Sub GrabDataFromWebsite() Dim IE As Object Dim HTMLDoc As Object Dim HTMLTable As Object Dim HTMLRow As Object Dim HTMLCell As Object ' 创建新的Internet Explorer对象 Set IE = CreateObject("InternetExplorer.Application") ' 打开网页 IE.navigate "https://www.example.com" ' 等待IE加载完成 Do While IE.Busy Or IE.readyState <> 4 DoEvents Loop ' 获取网页的HTML文档 Set HTMLDoc = IE.document ' 根据网页结构,定位到目标表格 Set HTMLTable = HTMLDoc.getElementById("tableID") ' 遍历表格的行和列,抓取数据 For Each HTMLRow In HTMLTable.Rows For Each HTMLCell In HTMLRow.Cells ' 在这里可以对数据进行处理或存储操作 MsgBox HTMLCell.innerText Next HTMLCell Next HTMLRow ' 关闭Internet Explorer对象 IE.Quit ' 清除对象变量的引用 Set IE = Nothing Set HTMLDoc = Nothing End Sub ``` 上述代码中,我们首先创建了一个Internet Explorer对象(IE),然后使用IE.navigate方法打开了指定的网页。在加载网页完成后,我们可以使用IE.document获取网页的HTML文档,并根据网页结构定位到目标数据所在的表格(或其他元素)。随后,使用For Each循环遍历表格的行和列,获取数据并进行处理或存储操作。最后,我们关闭IE对象并清除对象变量的引用。 需要注意的是,抓取网页数据时需要了解网页的HTML结构,以便准确定位需要抓取数据。此外,还可以根据需要使用其他方法和属性来处理网页中的数据,例如获取特定元素的属性值、点击按钮或链接等。 以上是一基本的抓取网页数据方法,在实际使用中还可以根据具体需求进行适当的修改和扩展。 ### 回答3: VBA抓取网页数据方法主要包括以下几个步骤: 1. 创建一个新的VBA宏,并在宏中引用"Microsoft Internet Controls"和"Microsoft HTML Object Library"这两个引用库。这些库将提供用于处理网页网页元素的对象和方法。 2. 使用Internet Explorer对象来打开要抓取数据网页。可以使用`Set ie = New InternetExplorer`来创建一个新的Internet Explorer对象,并使用`ie.Navigate`方法来打开指定的网页。 3. 等待网页加载完成。可以使用`Do While ie.Busy Or ie.ReadyState <> READYSTATE_COMPLETE`来等待网页加载完成。 4. 使用Document对象访问网页的HTML代码。可以使用`Set doc = ie.Document`来获取网页的Document对象,并使用`doc.getElementByID`、`doc.getElementsByTagName`等方法来定位网页中的元素。 5. 使用获取到的Document对象和元素对象来定位和提取需要的数据。可以使用元素对象的`innerText`、`getAttribute`等属性和方法来获取元素的文本内容或属性值。 6. 将获取到的数据保存到Excel等工作簿或其他数据源中。可以使用`Range`对象将数据写入到指定的单元格中,或使用ADO对象将数据插入到数据库中。 7. 关闭Internet Explorer对象,并释放相关资源。可以使用`ie.Quit`来关闭Internet Explorer对象。 需要注意的是,抓取网页数据时,应遵守网页的使用规定和法律法规,避免非法获取或滥用数据。同时,由于网页结构和数据可能会变化,需要根据具体网页的情况进行适当的调整和修改代码。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

主题模板站

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值