Python热榜

需要用到的库有:requests、beautifulsoup4、pandas、openpyxl

安装库:pip install requests、pip install beautifulsoup4、pip install pandas、pip install openpyxl

#!/usr/bin/python
# -*- coding:utf-8 -*-

import requests
from bs4 import BeautifulSoup
import pandas
import webbrowser
from tkinter import *
import tkinter as tk
from tkinter import ttk
from tkinter.filedialog import askdirectory

window = tk.Tk()
window.title("全网热搜")
window.geometry("640x480+500+100")
window.resizable(width=False, height=False)  # 不可调整窗口大小
lab1 = tk.Label(window, text="目标路径:")
lab2 = tk.Label(window, text="选择分类:")
path = StringVar()
menu = ttk.Combobox(window, width=10)
menu['value'] = ('知乎热榜', '微博热搜榜', '微信热文榜', 'bilibili日榜', '抖音视频榜')
input = tk.Entry(window, textvariable=path, width=45)  # 创建一个输入框显示存放路径
thebox = tk.Listbox(window, width=89, height=19)


# ------选取本地路径------
def select_path():
    path_ = askdirectory()
    path.set(path_)


# -------定义一个函数清除输出框第一行到最后一行的内容-----
def cle():
    thebox.delete(0, "end")


# -------选择爬取热搜的类别------
def get_cid():
    if menu.get() == "知乎热榜":
        cid = '/n/mproPpoq6O'
    if menu.get() == "微博热搜榜":
        cid = '/n/KqndgxeLl9'
    if menu.get() == "微信热文榜":
        cid = '/n/WnBe01o371'
    if menu.get() == "bilibili日榜":
        cid = '/n/74KvxwokxM'
    if menu.get() == "抖音视频榜":
        cid = '/n/DpQvNABoNE'
    return cid


# -----------获取响应解析内容---------
def download():
    base_url = 'https://tophub.today'
    url = base_url + str(get_cid())  # 最终解析链接
    headers = {
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36'}
    resp = requests.get(url, headers=headers)
    html = resp.text
    soup = BeautifulSoup(html, 'html.parser')
    nodes = soup.find('tbody').find_all('tr')  # 获取第一个tbody标签中的tr标签
    df = pandas.DataFrame()  # 初始化df
    lb = []  # 初始化lb
    for node in nodes:
        messages = node.find('td', class_='al').find_all('a')  # 获取所有a标签
        order = node.find('td', align='center').get_text()  # 获取排名
        heat = node.find_all('td')[2].get_text()  # 获取第二个td标签==热度
        for message in messages:
            title = message.get_text()  # 获取标题
            link = ['https://tophub.today' + message['href']]  # 获取链接
            lb = lb + link  # 将link循环写入到lb
            file_name = input.get() + '/' + menu.get() + '.xlsx'
            data = {
                '排名': [order],
                '热度': [heat],
                '标题': [title],
                '链接': link
            }
            item = pandas.DataFrame(data)
            df = pandas.concat([df, item])  # 合并表格
            df.to_excel(file_name, index=False)  # 写入表格到指定文件夹
        thebox.insert('end', (order, heat, title))  # 写入到展示框
    return lb


# -----------打开选中链接----------
def open_url():
    choice = thebox.curselection()[0]  # 获取选中的行号
    link = download()  # 调用download函数中的lb列表
    webbrowser.open(link[choice], new=1, autoraise=True)  # 用浏览器打开选中行对应的链接


# ----------用于选择保存路径-------
button0 = tk.Button(window, text='选择路径', relief=tk.RAISED, width=8, height=1, command=select_path)
# ----------用于paqu功能----------
button1 = tk.Button(window, text='爬取', relief=tk.RAISED, width=8, height=1, command=download)
# ----------用于清空输出框--------
button2 = tk.Button(window, text='清空输出', relief=tk.RAISED, width=8, height=1, command=cle)
# -----------用于打开链接----------
button3 = tk.Button(window, text='打开', width=8, height=1, command=open_url)

# -----------完成元素布局和设置部件位置---------
lab1.place(x=10, y=10)
lab2.place(x=10, y=60)
menu.place(x=90, y=60)
input.place(x=90, y=10)
thebox.place(x=5, y=110)
button0.place(x=540, y=5)
button1.place(x=420, y=55)
button2.place(x=540, y=55)
button3.place(x=300, y=55)
tk.mainloop()

 


 

工程文件(提取码:c4kj)

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 可以使用Python中的requests和BeautifulSoup库来爬取百度。下面是一个简单的代码示例: ```python import requests from bs4 import BeautifulSoup url = 'http://top.baidu.com/buzz?b=1&fr=topindex' response = requests.get(url) soup = BeautifulSoup(response.text, 'html.parser') # 获取列表 hot_list = soup.find_all('a', class_='list-title') # 输出标题 for hot in hot_list: print(hot.text) ``` 这个代码会输出当前百度的前20个点话题的标题。你可以根据需要对代码进行修改来获取更多信息。 ### 回答2: Python可以使用第三方库如BeautifulSoup和Requests实现对百度的爬取。首先,我们需要安装这些库,可以通过pip install命令在命令行中安装。 然后,我们需要导入这些库,以便在Python脚本中使用。导入BeautifulSoup和Requests库后,我们可以使用requests库发送HTTP请求,获取百度的网页内容。在请求中,我们可以使用用户代理,以防止被服务器阻止。 接下来,我们可以使用BeautifulSoup库对网页内容进行解析。我们可以找到网页中包含内容的HTML标签,并使用BeautifulSoup的一些方法来提取这些内容。例如,我们可以使用find方法根据标签名或属性来查找特定的元素,然后使用text属性来提取该元素的文本内容。 最后,我们可以将提取到的内容保存到一个文件中,以便后续的分析和处理。我们可以使用Python的文件操作方法,如open和write,来创建并写入文件。 总结起来,Python爬取百度的过程包括发送HTTP请求获取网页内容、使用BeautifulSoup解析网页内容、提取信息,并将其保存到文件中。这样,我们就可以方便地获取和处理百度的数据了。 ### 回答3: 要使用Python爬取百度,可以利用Python的网络爬虫库和数据处理库来实现。以下是一个简单的Python爬取百度的示例代码: ```python import requests from bs4 import BeautifulSoup url = 'https://top.baidu.com/board?tab=realtime' response = requests.get(url) soup = BeautifulSoup(response.text, 'html.parser') rankings = soup.find_all('a', class_='text-link') for ranking in rankings: title = ranking.text.strip() print(title) ``` 首先,我们导入`requests`和`BeautifulSoup`库,`requests`用于发送HTTP请求,`BeautifulSoup`用于解析HTML。然后,我们指定百度的URL,并发送GET请求获取网页内容。 使用BeautifulSoup解析网页内容后,我们可以通过查找HTML中特定的标签和class来提取我们想要的信息。在这个例子中,百度单标题使用`<a>`标签和`text-link`类来定义,因此我们使用`soup.find_all()`方法找到所有符合这一条件的元素。 最后,通过遍历这些元素,我们使用`.text`属性获取标题文本,并使用`.strip()`方法去除字符串两端的空格,最后将结果打印出来。 当然,这只是一个简单的示例,实际的爬虫项目可能需要更多的处理和调整,例如处理网页反爬虫机制、保存数据到数据库等。但是以上代码提供了一个基本的框架,用于理解如何使用Python爬取百度的基本步骤。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值