gpt4 book ai didi

PHP从网站爬取数据

转载 作者:行者123 更新时间:2023-11-29 12:54:27 24 4
gpt4 key购买 nike

我目前正在尝试从网站上抓取大量数据,但是我有点挣扎。它有一个 a-z 索引和 1-20 索引,所以里面有一堆循环和 DOM 东西。然而,它在第一次运行时成功地爬行并保存了大约 10,000 行,但现在我在 15,000 左右,每次运行只爬行了大约 100 行。

这可能是因为它必须跳过已经插入的行(对此进行了检查)。我想不出一种方法可以轻松跳过某些页面,因为 1-20 索引变化很大(一个字母有 18 页,其他字母只有 2 页)。

我正在检查是否已经存在具有给定 ID 的记录,如果没有,则插入它。我认为这会很慢,所以现在在脚本开始之前,我检索所有行,然后使用 in_array() 进行检查,假设这会更快。但它就是行不通。

所以我的爬虫正在导航 26 个字母,每个字母 20 页,然后每个页面最多 50 次,所以如果你计算一下,那就很多了。

考虑逐个字母地运行它,但这不会真正起作用,因为我仍然停留在“a”并且不能跳到“b”,因为我会错过“a”中的记录。

希望我已经很好地解释了这个问题,以便有人可以帮助我。我的代码有点像这样:(我在这里和那里删除了一些东西,猜测所有重要的东西都在这里给你一个想法)

function in_array_r($needle, $haystack, $strict = false) {
foreach ($haystack as $item) {
if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) {
return true;
}
}

return false;
}
/* CONNECT TO DB */
mysql_connect()......



$qry = mysql_query("SELECT uid FROM tableName");
$all = array();
while ($row = mysql_fetch_array($qru)) {
$all[] = $row;
} // Retrieving all the current database rows to compare later

foreach (range("a", "z") as $key) {
for ($i = 1; $i < 20; $i++) {
$dom = new DomDocument();
$dom->loadHTMLFile("http://www.crawleddomain.com/".$i."/".$key.".htm");
$finder = new DomXPath($dom);
$classname="table-striped";
$nodes = $finder->query("//*[contains(concat(' ', normalize-space(@class), ' '), ' $classname ')]");
foreach ($nodes as $node) {
$rows = $finder->query("//a[contains(@href, '/value')]", $node);
foreach ($rows as $row) {
$url = $row->getAttribute("href");
$dom2 = new DomDocument();
$dom2->loadHTMLFile("http://www.crawleddomain.com".$url);
$finder2 = new DomXPath($dom2);
$classname2="table-striped";
$nodes2 = $finder2->query("//*[contains(concat(' ', normalize-space(@class), ' '), ' $classname2 ')]");
foreach ($nodes2 as $node2) {

$rows2 = $finder2->query("//a[contains(@href, '/loremipsum')]", $node2);
foreach ($rows2 as $row2) {

$dom3 = new DomDocument();
//
// not so important variable declarations..
//


$dom3->loadHTMLFile("http://www.crawleddomain.com".$url);
$finder3 = new DomXPath($dom3);
//2 $finder3->query() right here


$query231 = mysql_query("SELECT id FROM tableName WHERE uid='$uid'");
$result = mysql_fetch_assoc($query231);
//Doing this to get category ID from another table, to insert with this row..
$id = $result['id'];


if (!in_array_r($uid, $all)) { // if not exist
mysql_query("INSERT INTO')"); // insert the whole bunch
}

}
}
}
}
}
}

最佳答案

$uid 未定义,而且此查询没有任何意义:

mysql_query("INSERT INTO')");

您应该打开错误报告:

ini_set('display_errors',1); 
error_reporting(E_ALL);

在查询之后,您应该执行or die(mysql_error());

而且,如果我不说,别人也会说。不要使用 mysql_* 函数。它们已被弃用,并将从 PHP 的 future 版本中删除。试试PDO .

关于PHP从网站爬取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24286585/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com