首页 > 解决方案 > Python网络抓取数值天气数据

问题描述

我正在尝试打印int 当前外部气温的值。(55)

有没有机会提示我做错了什么?(抱歉这里没有太多智慧!)

import requests
from bs4 import BeautifulSoup
import pandas as pd
import numpy as np
import datetime as dt

#this is used at the end with plotting results to current hour
h = dt.datetime.now().hour



r = requests.get(
'https://www.google.com/search?q=weather+duluth')
soup = BeautifulSoup(r.text, 'html.parser')

stuff = []

for item in soup.select('vk_bk sol-tmp'):
    item = int(item.contents[1].get_text(strip=True)[:-1])
    #print(item)#this is weather data
    stuff.append(item)

这是天气的 Web URL,当前室外温度与下面突出显示的 div 类相关联。

如果我尝试打印stuff,我只会返回一个空列表。 在此处输入图像描述

标签: pythonbeautifulsouppython-requests

解决方案


添加 User-Agent 标头应该会产生预期的结果

headers = {
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}

r = requests.get('https://www.google.com/search?q=weather%20duluth', headers=headers)
soup = BeautifulSoup(r.text, 'html.parser')

soup.find("span", {"class": "wob_t"}).text


推荐阅读