python - 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 类相关联。
解决方案
添加 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
推荐阅读
- vue.js - 在另一个选项卡中显示工具栏 crud 表
- exe - 如何将SB3制作成exe
- java - 如何访问特定文件夹并使用 Scoped Storage 将文件写入其中
- events - Chai closeTo 谈以太坊活动
- ignite - 集群掉电如何快速恢复?
- google-sheets - 如何基于一个标题组合来自 2 张工作表的数据
- ruby - 如何在 ZendeskAPI ruby gem 中进行分页?
- python - 如何打印列表中特定元素之后的所有元素?
- reactjs - 无法从 Firestore 数据库中获取数据
- r - 在 R 中创建具有 rdrobust 输出的 stargazer 表