你可以使用 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')
2207

被折叠的 条评论
为什么被折叠?



