一、概述

1.1 需求

以合集搜索链接为例,可根据需求自己替换:https://www.hacg.mov/wp/page/1?s=%E5%90%88%E9%9B%86&submit=%E6%90%9C%E7%B4%A2

主要匹配所有a标签中的关键词 "月合集"的链接,然后 for 循环提取链接中的磁力链接

1.2 基础环境

Python Version: Python 3.10
依赖库:BeautifulSoup re requests

1.3 安装库

pip3 install BeautifulSoup re requests

二、源码

import requests
from bs4 import BeautifulSoup
import re

# 请求网页,url page页参数值自己修改,如果要找往期的合集,就改成2.3.4 ...
url = 'https://www.hacg.mov/wp/page/1?s=%E5%90%88%E9%9B%86&submit=%E6%90%9C%E7%B4%A2'
response = requests.get(url)
html_content = response.text

# 解析HTML
soup = BeautifulSoup(html_content, 'html.parser')

# 查找所有<a>标签并打印,提取所有每月合集的链接
links = {}
for a_tag in soup.find_all('a'):
    href = a_tag.get('href')
    text = a_tag.get_text(strip=True)
    if "月合集" in text:
        links.update({"{}".format(text): "{}".format(href)})


# 请求每月合集的链接,获取磁力链接,并存储到新字典中
magnet_links = {}
for i in links.keys():
    url = links[i]
    response = requests.get(url)

    if response.status_code == 200:
        content = response.text

        matches = re.findall(r'\b[a-f0-9]{40}\b', content)
    
        # 如果找到了匹配项,则将第一个匹配项存入字典
        if matches:
            magnet_links[i] = "magnet:?xt=urn:btih:" + matches[0]
    else:
        print(f"请求失败,状态码: {response.status_code}")

print(magnet_links)

执行结果:

python3 hacg_spider.py
{'2024年06月合集': 'magnet:?xt=urn:btih:423a7e4677193d3ce71de16152e341001e990352', '2024年05月合集': 'magnet:?xt=urn:btih:453bb0d3a5dcf082fb9b46c5cdc11d766de49406', '2024年04月合
集': 'magnet:?xt=urn:btih:b496ccad674d6aa8c180e317747627ac01ecb23a', '2024年03月合集': 'magnet:?xt=urn:btih:3ca3e98867bc5571b21a76bb8f76b13279f5c25a', '2024年02月合集': 'magnet:?xt=urn:btih:fe4febd0581492f01c583ca2201c9af7ef697365', '2024年01月合集': 'magnet:?xt=urn:btih:14a6d8231d9a6095fd2f53e05d47c319643201af'}
END
本文作者:
文章标题: 使用python爬取琉璃神社每月合集磁力链
本文地址: https://blog.imwlw.com/archives/4/
版权说明:若无注明,本文皆 ITShare Studio 原创,转载请保留文章出处。
最后修改:2024 年 08 月 26 日
如果觉得我的文章对你有用,请随意赞赏