WordPress 自动采集 TorrentMac 应用文章并发布
以下代码示例演示如何使用 WordPress 的 wp_remote_request 等函数,从 TorrentMac 的应用分类页面获取文章链接,提取标题和 Torrent 链接,并自动发布到 WordPress 网站。
function get_torrent_links() {
$url = 'https://www.torrentmac.net/category/applications/';
$response = wp_remote_request( $url, array(
'timeout' => 10,
'sslverify' => false,
) );
if ( is_wp_error( $response ) ) {
return;
}
$body = wp_remote_retrieve_body( $response );
$doc = new DOMDocument();
@$doc->loadHTML( $body );
$links = array();
$items = $doc->getElementsByTagName( 'article' );
foreach ( $items as $item ) {
$title = $item->getElementsByTagName( 'h2' )->item(0)->textContent;
$link = $item->getElementsByTagName( 'a' )->item(0)->getAttribute( 'href' );
$torrent_link = get_torrent_link( $link );
$links[] = array(
'title' => $title,
'link' => $torrent_link,
);
}
return $links;
}
function get_torrent_link( $url ) {
$response = wp_remote_request( $url, array(
'timeout' => 10,
'sslverify' => false,
) );
if ( is_wp_error( $response ) ) {
return;
}
$body = wp_remote_retrieve_body( $response );
$doc = new DOMDocument();
@$doc->loadHTML( $body );
$link = '';
$items = $doc->getElementsByTagName( 'a' );
foreach ( $items as $item ) {
if ( strpos( $item->getAttribute( 'href' ), 'magnet:' ) !== false ) {
$link = $item->getAttribute( 'href' );
break;
}
}
return $link;
}
function publish_torrent_articles() {
$links = get_torrent_links();
foreach ( $links as $link ) {
$post = array(
'post_title' => $link['title'],
'post_content' => $link['link'],
'post_status' => 'publish',
'post_author' => 1,
'post_type' => 'post',
'comment_status' => 'closed',
'ping_status' => 'closed',
);
$post_id = wp_insert_post( $post );
}
}
add_action( 'wp_ajax_nopriv_publish_torrent_articles', 'publish_torrent_articles' );
add_action( 'wp_ajax_publish_torrent_articles', 'publish_torrent_articles' );
代码说明:
get_torrent_links函数从 TorrentMac 应用分类页面获取文章链接,并提取标题和 Torrent 链接。get_torrent_link函数从文章链接中提取 Torrent 链接。publish_torrent_articles函数将获取到的文章标题和 Torrent 链接发布到 WordPress 网站。- 在
wp_remote_request函数中,sslverify参数设置为false,这可能存在安全风险,建议根据实际情况调整。 - 代码使用
wp_insert_post函数发布文章,可以根据需要调整参数。 - 最后,代码将
publish_torrent_articles函数添加到 WordPress 的 AJAX 钩子中,以便在前台页面上调用。
注意:
- 本代码示例仅供参考,请在使用前充分了解其风险,并进行必要的修改和安全检查。
- 从其他网站抓取数据需要遵循相关法律法规,并尊重网站的 robots.txt 协议。
- 建议使用更安全的方式进行网络请求,例如使用 HTTPS 和 SSL 证书验证。
- 为了提高效率和安全性,可以使用其他工具和技术,例如 cURL 库、Guzzle 等。
- 在发布文章前,建议先进行内容审核,以确保内容的合法性和安全性。
原文地址: https://www.cveoy.top/t/topic/lQwF 著作权归作者所有。请勿转载和采集!