python爬虫实战(7)--获取it某家热榜

1. 需要的类库

import requests
from bs4 import BeautifulSoup
import pandas as pd

2. 请求榜单

def fetch_ranking_data():
    url = "https://m.ithome.com/rankm/"
    response = requests.get(url)

    if response.status_code == 200:
        return response.content
    else:
        print(f"Error fetching data. Status code: {response.status_code}")
        return None

3. 解析响应

def parse_html(html_content):
    soup = BeautifulSoup(html_content, 'html.parser')
    rank_items = soup.find_all('div', class_='placeholder one-img-plc')

    data = []
    for rank_item in rank_items:
        rank_num = rank_item.select_one('.rank-num').text
        title = rank_item.select_one('.plc-title').text
        url = rank_item.select_one('a')['href']

        data.append({
            'Rank': rank_num,
            'Title': title,
            'URL': url
        })

    return data

4.输出文件

def create_excel(data):
    df = pd.DataFrame(data)
    df.to_excel('ranking_data.xlsx', index=False)
    print("Excel file created successfully.")

5. 成果展示

在这里插入图片描述

相关推荐

  1. python爬虫实战(6)--获取

    2024-01-11 08:18:03       36 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-01-11 08:18:03       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-01-11 08:18:03       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-01-11 08:18:03       19 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-01-11 08:18:03       20 阅读

热门阅读

  1. Vue3中的`ref`和`reactive使用中遇到的一些坑

    2024-01-11 08:18:03       34 阅读
  2. ReactHooks:渲染与useState

    2024-01-11 08:18:03       38 阅读
  3. zmq_connect和zmq_poll

    2024-01-11 08:18:03       22 阅读
  4. 01-04css

    01-04css

    2024-01-11 08:18:03      30 阅读
  5. pnp4nagios 配置 nagios

    2024-01-11 08:18:03       32 阅读
  6. C语言中顺序栈的实现与表示

    2024-01-11 08:18:03       33 阅读