我将这个简单的Web Weather Scraping
脚本放在一起,以检查给定位置的温度。代码运行完美,即使它可能不是最好或最干净的版本。还在学习。但它正在抓取:<span _ngcontent-c19="" class="wu-value wu-value-to">67</span>
来自HERE。
#!/usr/bin/python
# -*- coding: utf-8 -*-
import requests
from BeautifulSoup import BeautifulSoup
import time
degree = u'\N{DEGREE SIGN}'
url = 'https://www.wunderground.com/weather/us/ca/san-diego/KCASANDI355'
response = requests.get(url)
html = response.content
soup = BeautifulSoup(html)
current_temp = soup.find("div", {"class" : "current-temp"}).find("span", {"class" : "wu-value wu-value-to"})
for i in current_temp:
print('San Diego Feels Like ') + i + (degree + 'F')
输出如下所示:
San Diego Feels Like 74°F
我的目标是拥有一个循环功能,并根据current_temp
变量中定义的当前温度打印,例如,如果温度低于70F It's too cold
,或者如果它超过80F It is too hot
等
但是我有一个问题是要了解如何告诉我的代码执行,或者在这种情况下print
这些不同的任务或方法你可以说?请原谅我的英语。 While (True):
循环肯定有问题,但我无法理解它。感谢您的帮助,祝大家周日愉快。
#!/usr/bin/python
import requests
from BeautifulSoup import BeautifulSoup
import time
degree = u'\N{DEGREE SIGN}'
url = 'https://www.wunderground.com/weather/us/ca/san-diego/KCASANDI355'
response = requests.get(url)
html = response.content
soup = BeautifulSoup(html)
current_temp = soup.find("div", {"class" : "current-temp"}).find("span", {"class" : "wu-value wu-value-to"})
def weather():
while(True):
for i in current_temp:
print('San Diego Feels Like ') + i + (degree + 'F')
#time.sleep(2)
if (i <= 70) and (i >= 50):
print('It\'s kinda cool')
break
elif i <= 50:
print('It\'s cold af')
elif (i >= 80) and (i <= 100):
print('It\'s hot af')
break
else:
print('You Dead')
break
if __name__ == "__main__":
weather()
答案 0 :(得分:1)
首先,你正在收集整个<span>
标签,即使你只对所呈现的值感兴趣,所以要获得温度值(并将其转换为实际整数),请执行:
current_temp = int(soup.find("div", {"class": "current-temp"}).find(
"span", {"class": "wu-value wu-value-to"}).getText())
其次,你的current_temp
一旦获得就永远不会改变,你想要的是定期拿起最新的温度值,然后根据它的值,打印你想要的任何东西。类似的东西:
# !/usr/bin/python
import requests
from BeautifulSoup import BeautifulSoup
import time
degree = u'\N{DEGREE SIGN}'
url = 'https://www.wunderground.com/weather/us/ca/san-diego/KCASANDI355'
def weather():
while (True):
# get the current temperature
response = requests.get(url)
soup = BeautifulSoup(response.content)
current_temp = int(soup.find("div", {"class": "current-temp"}).find(
"span", {"class": "wu-value wu-value-to"}).getText())
# now print it out and add our comment
print(u"San Diego Feels Like: {}{}F".format(current_temp, degree))
if current_temp > 100:
print("You Dead")
elif 100 >= current_temp > 80:
print("It's hot af")
elif 80 >= current_temp > 70:
print("It's just right")
elif 70 >= current_temp > 50:
print("It's kinda cool")
else:
print("It's cold af")
# finally, wait 5 minutes (300 seconds) before updating again
time.sleep(300)
if __name__ == "__main__":
weather()