php代码|采集爱站“相关词”,然后写入html页面(php采集网页数据)

时间:2023-07-05 03:02:15   阅读:373
  1. 第一个思路是先用php代码采集 相关词 写入guanjianci.txt文件。代码如下:

效果图:php代码|采集爱站“相关词”,然后写入html页面(php采集网页数据)

<?php

// 设置要抓取的网页地址
$urls = array(
    'https://ciku.aizhan.com/c135/relatedwords/',
    'https://ciku.aizhan.com/c135/relatedwords_2/',
    'https://ciku.aizhan.com/c135/relatedwords_3/',
    'https://ciku.aizhan.com/c135/relatedwords_4/',
    'https://ciku.aizhan.com/c135/relatedwords_5/'
);

// 遍历每个页面
foreach ($urls as $url) {
  
    // 抓取网页内容
    $html = file_get_contents($url);
  
    // 解析 HTML
    $dom = new DOMDocument();
    @$dom->loadHTML($html);
  
    // 获取所有 <td class="title"> 标签
    $tds = $dom->getElementsByTagName('td');
  
    // 遍历所有标签,找到 class="title" 的标签
    foreach ($tds as $td) {
        if ($td->getAttribute('class') === 'title') {
            // 获取标签内的网址和中文内容
            $link = $td->getElementsByTagName('a')->item(0)->getAttribute('href');
            $text = trim($td->nodeValue);
          
            // 将结果写入文件
            file_put_contents('guanjianci.txt', $link . ' ' . $text . PHP_EOL, FILE_APPEND);
        }
    }
}
?>


2.利用php代码写入html网页output.html,代码如下:

<?php

// 打开 guanjianci.txt 文件,读取所有行
$lines = file('guanjianci.txt');

// 打开 output.html 文件以写入方式
$fp = fopen('output.html', 'w');

// 遍历每一行,将 HTML 写入文件
foreach ($lines as $line) {
    // 分离出网址和文本内容
    list($url, $text) = explode(' ', trim($line), 2);

    // 构造 HTML <a> 标签
    $html = "1
    <a href='$url'>$text</a><br>\n
    ";
  
    // 将 HTML 写入文件
    fwrite($fp, $html);
}

// 关闭文件
fclose($fp);

echo 'HTML 写入完毕。';
?>


上一篇:爆裂连击!掌握暗区突围卡网的技巧

下一篇:PUBG国际服挂:如何平衡市场需求与游戏的公平性?

网友评论