求助:如何用Python/Jquery从其他URL复制Div HTML到WordPress网站?
两种实现方案:JQuery前端 + Python后端
一、JQuery 前端实现(结合WordPress AJAX)
直接前端跨域请求会触发浏览器同源策略,必须通过WordPress的AJAX接口做中转:
- 在主题的
functions.php中添加AJAX处理逻辑:
function fetch_external_div() { $url = $_POST['target_url']; $div_selector = $_POST['div_selector']; // 抓取目标页面内容 $response = wp_remote_get($url); if (is_wp_error($response)) { wp_send_json_error('抓取失败'); exit; } $html = wp_remote_retrieve_body($response); // 解析HTML获取目标Div $dom = new DOMDocument(); @$dom->loadHTML($html); $xpath = new DOMXPath($dom); $divs = $xpath->query($div_selector); if ($divs->length > 0) { $target_html = $dom->saveHTML($divs->item(0)); wp_send_json_success($target_html); } else { wp_send_json_error('未找到目标Div'); } exit; } add_action('wp_ajax_fetch_external_div', 'fetch_external_div'); add_action('wp_ajax_nopriv_fetch_external_div', 'fetch_external_div'); // 允许未登录用户访问
- 在页面添加JQuery调用代码(可放在自定义HTML块或主题
footer.php):
jQuery(document).ready(function($) { // 替换为你的目标URL和Div选择器 var targetUrl = 'https://example.com/target-page'; var divSelector = '#target-div'; $.ajax({ url: '/wp-admin/admin-ajax.php', type: 'POST', data: { action: 'fetch_external_div', target_url: targetUrl, div_selector: divSelector }, success: function(response) { if (response.success) { // 将内容插入到页面指定容器 $('#your-container').html(response.data); } else { $('#your-container').html('加载失败:' + response.data); } }, error: function() { $('#your-container').html('请求出错'); } }); });
- 页面中添加展示容器:
<div id="your-container"></div>
二、Python 后端实现(通过Cpanel部署)
适合预先抓取内容再展示,或需要复杂处理的场景:
- 编写Python抓取脚本(命名为
fetch_div.py),上传到Cpanel文件管理器:
import requests from bs4 import BeautifulSoup def fetch_div_content(url, div_selector): try: response = requests.get(url) response.raise_for_status() soup = BeautifulSoup(response.text, 'html.parser') target_div = soup.select_one(div_selector) return str(target_div) if target_div else None except Exception as e: print(f"抓取错误:{e}") return None # 示例调用,可根据需求修改存储逻辑 if __name__ == '__main__': target_url = 'https://example.com/target-page' div_selector = '#target-div' div_html = fetch_div_content(target_url, div_selector) if div_html: # 将内容写入服务器文件 with open('/home/你的Cpanel用户名/public_html/div_content.html', 'w') as f: f.write(div_html)
安装依赖:在Cpanel终端执行
pip install requests beautifulsoup4(若不支持终端,可联系主机商安装)。设置定时任务:在Cpanel的「Cron Jobs」中添加定时规则,例如每天凌晨执行一次:
0 0 * * * python /home/你的Cpanel用户名/public_html/fetch_div.py
- 在WordPress中调用内容:在页面模板或自定义HTML块中加入:
<?php $div_content_file = ABSPATH . 'div_content.html'; echo file_exists($div_content_file) ? file_get_contents($div_content_file) : '暂无内容'; ?>
注意事项
- 确认目标网站允许抓取,遵守其
robots.txt规则。 - 控制抓取频率,避免触发目标网站反爬机制。
- WordPress AJAX接口可添加nonce验证提升安全性。
内容的提问来源于stack exchange,提问作者Mamadona
相关产品推荐
相关产品推荐

