使用django抓取天气页面的数据

你可以使用 Django 的视图函数结合 Python 的 requests 库来抓取百度首页的页面。以下是一个简单的示例:

首先,确保你已经安装了 requests 库:

pip install requests

然后,在你的 Django 项目中创建一个视图函数,例如:

# views.py

from django.shortcuts import render
import requests

def baidu_index(request):
    url = 'https://www.baidu.com/'
    response = requests.get(url)
    content = response.text
    return render(request, 'baidu_index.html', {'content': content})

使用BeautifulSoup

Beautiful Soup 是一个用于解析 HTML 和 XML 文档的 Python 库。它能够从网页中提取数据,并提供简单而直观的方式来遍历文档树、搜索特定的标签或内容,以及对文档进行修改。

在 Django 中,你可以使用 BeautifulSoup 来解析从网页中获取的 HTML 内容,从而方便地提取需要的信息。通常情况下,结合 Django 中的视图函数和模板,可以实现从网页中抓取数据并展示在页面上的功能。

以下是一个简单的示例,展示了如何在 Django 中使用 BeautifulSoup:

# views.py

from django.shortcuts import render
import requests
from bs4 import BeautifulSoup

def baidu_index(request):
    url = 'https://www.baidu.com/'
    response = requests.get(url)
    soup = BeautifulSoup(response.text, 'html.parser')
    # 提取百度首页的标题
    title = soup.title.string
    return render(request, 'baidu_index.html', {'title': title})

具体获取天气页面数据的代码:

# 设置要预设的城市信息
            city_id = 58362
            city_pinyin = 'shanghai'

            # 构造要发送的 cookie
            cookies = {
                'lastCountyId': str(city_id),
                'lastCountyPinyin': city_pinyin,
                'lastCountyTime': '1708913263',
                'defaultCityID': str(city_id),
                'defaultCityPinyin': city_pinyin
            }

            # 发送 GET 请求并传递 cookie
            url = "https://tianqi.2345.com/Pc"
            response = requests.get(url, cookies=cookies)

            if response.status_code == 200:
                soup = BeautifulSoup(response.text, 'html.parser')
                # 获取7天天气
                box_mods = soup.find_all('ul', class_='weaday7')
                weather_contents = [str(box_mod) for box_mod in box_mods]
# 获取生活指南
                box_mods2 = soup.find_all('ul', class_='life-index')
                weather_contents2 = [str(box_mod2) for box_mod2 in box_mods2]
                # 获取温度排行榜
                box_mods3 = soup.find_all('div', class_='rank-temperature')
                weather_contents3 = [str(box_mod3) for box_mod3 in box_mods3]
                # 空气排行榜
                box_mods4 = soup.find_all('div', class_='rank-airquality')
                weather_contents4 = [str(box_mod4) for box_mod4 in box_mods4]
                # 当天天气
                box_mods5 = soup.find_all('div', class_='info-box-wrap-left')
                weather_contents5 = [str(box_mod5) for box_mod5 in box_mods5]
                # 获取实时温度

                box_mod6 = soup.find('div', class_='info-box-wrap-left')

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值