【问题标题】:How To Insert Links Scraped With DOM Into A MySQL Database? (or what am I doing wrong?)如何将使用 DOM 抓取的链接插入 MySQL 数据库? (或者我做错了什么?)
【发布时间】:2011-03-21 08:21:15
【问题描述】:

我正在整理一个 php 脚本,该脚本使用 curl 提取 html,将其复制到新页面并保存页面名称。所有这些都有效,但我还想收集页面上的 url 并将它们输入数据库。根据我的研究,看起来 DOM 是最好的方法。但是,当我在代码中包含 DOM 时,我得到“错误,插入查询失败”。 Here 是我获取 DOM 代码的地方。我怀疑这是一个数据库问题。

DOM、PHP 和 MySQL 对我来说是新的,所以任何 cmets、指针或建议都会有所帮助和赞赏。

任何关于整体方法的 cmets 或替代建议也非常受欢迎。我并不完全相信 DOM 最适合从 html 中抓取 url。

<html>
<body>

<?
$urls=explode("\n", $_POST['url']);
$proxies=explode("\n", $_POST['proxy']);

for ( $counter = 0; $counter <= 6; $counter++) {
for ( $count = 0; $count <= 6; $count++) {

 $ch = curl_init();
 curl_setopt($ch, CURLOPT_URL,$urls[$counter]);
 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 0);
 curl_setopt($ch, CURLOPT_PROXY,$proxies[$count]);
 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
 curl_setopt($ch, CURLOPT_CUSTOMREQUEST,'GET');
 curl_setopt ($ch, CURLOPT_HEADER, 1); 
curl_exec ($ch); 
$curl_scraped_page = curl_exec($ch); 

$FileName = rand(0,100000000000);
$FileHandle = fopen($FileName, 'w') or die("can't open file");
fwrite($FileHandle, $curl_scraped_page);


$dom = new DOMDocument();
@$dom->loadHTML($curl_scraped_page);
$xpath = new DOMXPath($dom);
$hrefs = $xpath->evaluate("/html/body//a");

$hostname="****";
$username="****";
$password="****";
$dbname="leadturtle";
$usertable="happyturtle";

$con=mysql_connect($hostname,$username, $password) or die ("<html><script language='JavaScript'>alert('Unable to connect to database! Please try again later.'),history.go(-1)</script></html>");
mysql_select_db($dbname ,$con);



function storeLink($url) {
    $query = "INSERT INTO happyturtle (time, ad1, ad2) VALUES ('$FileName','$url', '$gathered_from')";
    mysql_query($query) or die('Error, insert query failed');
}
for ($i = 0; $i < $hrefs->length; $i++) {
    $href = $hrefs->item($i);
    $url = $href->getAttribute('href');
    storeLink($url,$target_url);

}


mysql_close($con);

fclose($FileHandle);

curl_close($ch);

echo $FileName; 

echo "<br/>";

}
}

?>

</body>
</html>

【问题讨论】:

  • @user586011:请奖励帮助过您的人,并接受您对旧问题的回答。谢谢。

标签: php mysql html url dom


【解决方案1】:

您没有转义 SQL 查询中的值。

如果您的字符串参数包含 ' ,则会导致语法错误(最好的情况)。 但它也可能导致源注入和大的安全漏洞 (http://xkcd.com/327/ :)!

首先检查您的输入。

请在您的问题中添加 hte 错误消息。

【讨论】:

    猜你喜欢
    • 2015-11-19
    • 2018-11-04
    • 2014-07-23
    • 1970-01-01
    • 2020-10-25
    • 1970-01-01
    • 1970-01-01
    • 2021-04-17
    • 1970-01-01
    相关资源
    最近更新 更多