php代码/js代码|php获取百度热榜写入txt文件,然后用js代码读取展示
时间:2023-06-16 21:09:49 阅读:901
标题一样的内容
php代码:
<?php // 创建 DOM 解析器对象 $dom = new DOMDocument(); // 禁用错误报告(忽略无效的 HTML) libxml_use_internal_errors(true); // 加载页面内容 $dom->loadHTMLFile("https://top.baidu.com/board?tab=realtime"); // 重置错误报告 libxml_clear_errors(); // 获取指定元素内容 $xpath = new DOMXPath($dom); $elements = $xpath->query('//a[@class="title_dIF3B "]'); $contentString = ""; foreach ($elements as $element) { $textContent = $element->getElementsByTagName('div')[0]->nodeValue; $href = $element->getAttribute("href"); $contentString .= $textContent . " (" . $href . ")" . "\n"; } // 写入文件 $file = fopen("resou.txt", "w"); fwrite($file, $contentString); fclose($file); ?>
js代码:
<script> fetch('resou.txt') .then(response => response.text()) .then(data => { const lines = data.split('\n'); lines.forEach(line => { line = line.trim(); if (line !== '') { // Extract the URL enclosed within parentheses const urlMatches = line.match(/\((.*?)\)/); let url = ""; if (urlMatches && urlMatches.length > 1) { url = urlMatches[1]; } // Remove any text within parentheses const content = line.replace(/\(.*?\)/g, '').trim(); // Create the <a> tag with the URL and content const aTag = document.createElement('a'); aTag.href = url; aTag.textContent = content; // 留意这个,是在a标签内添加东西Add class="logo" and target="_blank" attributes to the <a> tag aTag.className = 'logo'; aTag.target = '_blank'; // Append the <a> tag to the body or any other element document.body.appendChild(aTag); // Add line break after each <a> tag const brTag = document.createElement('br'); document.body.appendChild(brTag); } }); }) .catch(error => console.error(error)); </script>
网友评论