【发布时间】:2018-09-17 11:23:21
【问题描述】:
我在php 中编写了一个脚本来抓取不同的title 帖子及其links,并将它们从网页写入一个csv 文件。我希望在column A 中写titles 及其相关的links 在column B 中。当我将它们写在单个列中时,脚本就可以完成这项工作。但是,由于我不知道如何在多列中写入数据,所以我卡住了。
目前它正在将 titles 写入 csv 文件,因为我已经在脚本中注释掉了 links 部分,只是因为我不知道如何在 column B 中编写它们。任何解决问题的帮助将不胜感激。
这是我尝试过的:
<?php
include "simple_html_dom.php";
$url = "https://stackoverflow.com/questions/tagged/web-scraping";
function get_information($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
$htmlContent = curl_exec($ch);
curl_close($ch);
$dom = new simple_html_dom();
$dom->load($htmlContent);
$links = array();
$file = fopen("outputfile.csv","w");
foreach ($dom->find('.question-hyperlink') as $link) {
fputcsv($file,array($link->innertext));
//fputcsv($file,array($link->href));
}
fclose($file);
}
get_information($url);
?>
【问题讨论】:
标签: php csv curl dom web-scraping