(Python代码)
闲的没事,想做一个Python爬虫气象站
源代码:
from tkinter import *
from bs4 import BeautifulSoup
import requests
root = Tk()
def findweather():
responce = requests.get("http://www.weather.com.cn/weather/101121201.shtml")
responce.encoding="urf-8"
soup=BeautifulSoup(responce.text,"html.parser")
div=soup.find("div",id="7d")
ul=div.find("ul")
li=ul.find_all("li")
weatherForSevenDay=[]
for weather in li:
temp=[]
date=weather.find("h1").string
temp.append(date)
p=weather.find_all("p")
weatherDetail=p[0].string
if weatherDetail is not None :
temp.append("天气为:%s" % weatherDetail)
Hightemprature=p[1].find("span").string
if Hightemprature is not None :
temp.append("最高温为:%s ℃" % Hightemprature)
Lowtemprature=p[1].find("i").double
if Lowtemprature is not None :
temp.append("最低温为:%s ℃" % Lowtemprature)
weatherForSevenDay.append(temp)
for weather in weatherForSevenDay:
print(weather)
root.geometry("700x400")
root.title("家庭气象站")
label_1=Label(root,text="家庭气象站—首页",bg="cyan")
label_1.pack(fill = X ,padx=10)
button=Button(root,text="直接显示天气(在Pyhon Shell中查看)",command=findweather)
button.pack()
root.mainloop()
结果报错:
Exception in Tkinter callback
Traceback (most recent call last):
File "D:\lib\tkinter\__init__.py", line 1705, in __call__
return self.func(*args)
File "C:/Users/Administrator/Desktop/家庭气象站/家庭气象站.py", line 22, in findweather
Hightemprature=p[1].find("span").string
AttributeError: 'NoneType' object has no attribute 'string'
bd无果,所以前来求助万能谷民