吾爱破解 - LCG - LSG |安卓破解|病毒分析|www.52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 797|回复: 6
收起左侧

[求助] 工作需要写了段爬取网页发布公告内容的代码,怎么才能让它拥有点击标题进入跟翻页

[复制链接]
suneryzgg123 发表于 2024-1-12 21:20
只写了一点点简陋的代码,只能爬取指定网页内的文本内容,但是我要爬取的内容需要点击标题进入才行,还有翻页这个难题,有大手子帮忙瞅瞅吗?
[Python] 纯文本查看 复制代码
import requests
from bs4 import BeautifulSoup
import tkinter as tk
from tkinter import filedialog
from tkinter import messagebox
from datetime import datetime

def get_web_content(url, keywords, start_date, output_dir):
    try:
        # 发送GET请求
        response = requests.get(url)
        # 检查响应状态码
        if response.status_code == 200:
            # 解析HTML内容
            soup = BeautifulSoup(response.content, 'html.parser')
            # 获取所有文本内容
            text_content = soup.get_text()
            # 检查关键词
            if keywords:
                text_content = filter_keywords(text_content, keywords)
            # 检查发布时间
            if start_date:
                text_content = filter_by_date(text_content, start_date)
            # 保存内容到文件
            save_to_file(text_content, output_dir)
            messagebox.showinfo("成功", "内容获取成功并保存到 " + output_dir)
        else:
            messagebox.showerror("错误", "无法获取网站内容,状态码:" + str(response.status_code))
    except Exception as e:
        messagebox.showerror("错误", "发生异常:" + str(e))

def filter_keywords(content, keywords):
    # 在内容中筛选关键词
    return "\n".join([line for line in content.split("\n") if any(keyword in line for keyword in keywords)])

def filter_by_date(content, start_date):
    # 在内容中筛选发布时间
    lines = content.split("\n")
    filtered_lines = []
    for line in lines:
        if is_date_after(line, start_date):
            filtered_lines.append(line)
    return "\n".join(filtered_lines)

def is_date_after(line, start_date):
    # 检查行中是否包含日期,并判断是否在指定日期之后
    try:
        date_str = line.split()[0]
        date = datetime.strptime(date_str, '%Y-%m-%d')
        return date >= start_date
    except Exception as e:
        return False

def save_to_file(content, output_dir):
    # 保存内容到文件
    with open(output_dir, 'w', encoding='utf-8') as file:
        file.write(content)

def main():
    # 创建GUI窗口
    window = tk.Tk()
    window.title("网站内容获取工具")

    # 添加网址输入框
    url_label = tk.Label(window, text="网址:")
    url_label.pack()
    url_entry = tk.Entry(window, width=50)
    url_entry.pack()

    # 添加关键词输入框
    keywords_label = tk.Label(window, text="关键词(用逗号分隔):")
    keywords_label.pack()
    keywords_entry = tk.Entry(window, width=50)
    keywords_entry.pack()

    # 添加发布时间输入框
    date_label = tk.Label(window, text="发布时间(格式:YYYY-MM-DD):")
    date_label.pack()
    date_entry = tk.Entry(window, width=50)
    date_entry.pack()

    # 添加存放路径选择按钮
    def choose_dir():
        output_dir = filedialog.asksaveasfilename(defaultextension=".txt", filetypes=[("Text files", "*.txt")])
        output_dir_entry.delete(0, tk.END)
        output_dir_entry.insert(0, output_dir)

    output_dir_label = tk.Label(window, text="存放路径:")
    output_dir_label.pack()
    output_dir_entry = tk.Entry(window, width=50)
    output_dir_entry.pack()
    choose_dir_button = tk.Button(window, text="选择路径", command=choose_dir)
    choose_dir_button.pack()

    # 添加获取内容按钮
    def get_content():
        url = url_entry.get()
        keywords = keywords_entry.get().split(",")
        start_date_str = date_entry.get()
        output_dir = output_dir_entry.get()
        start_date = datetime.strptime(start_date_str, '%Y-%m-%d') if start_date_str else None
        get_web_content(url, keywords, start_date, output_dir)

    get_content_button = tk.Button(window, text="获取内容", command=get_content)
    get_content_button.pack()

    # 运行GUI程序
    window.mainloop()

if __name__ == "__main__":
    main()

发帖前要善用论坛搜索功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

一生挚爱不回头 发表于 2024-1-12 21:29
抓包就行了  好像没看见网址
ericwise 发表于 2024-1-12 21:44
才不是弱受 发表于 2024-1-12 21:56
EchoAria 发表于 2024-1-13 00:28
可以用selenium嘛?或者直接抓取数据接口呢
挣扎的时候 发表于 2024-1-13 07:46
谢谢分享
assuller 发表于 2024-1-13 08:03
本帖最后由 assuller 于 2024-1-13 08:05 编辑

看你注释写的这么详细,就帮帮你吧!!
1.功能1点击页面的实现:首先你需要解析首页需要点进去的链接规律。如果有规律那就可以用for循环实现切换页面,如果没有规律那你可以使用解析页面链接的方式获取超链接,然后对获取的链接再次进行解析就实现了点击不同标题的功能。
2.功能2实现翻页的功能:原理基本和功能1差不多,翻页基本都是有规律的,可以通过for i in range(1,20)循环获取值,然后将获取值赋值到f'www.example.com/index/{num}.html'的链接中进行解析,就实现了翻页功能。
核心:功能1需要在功能2的循环下循环才能够实现翻页后再对页面进行解析
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则 警告:本版块禁止回复与主题无关非技术内容,违者重罚!

快速回复 收藏帖子 返回列表 搜索

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - LCG - LSG ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2024-6-4 01:24

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表