阅读目录
1 headers = { 2 "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36", 3 } 4 5 def getWeath(city_code): 6 try: 7 url = f'http://www.weather.com.cn/weather/{city_code}.shtml' 8 resp = requests.get(url, headers = headers) 9 except BaseException as e: 10 print(e) 11 return {} 12 13 resp.encoding = 'utf-8'14 soup = BeautifulSoup(resp.text, 'html.parser') 15 tagToday = soup.find('p', class_ = "tem") #第一个包含class="tem"的p标签即为存放今天天气数据的标签16 try: 17 temperatureHigh = tagToday.span.string #有时候这个最高温度是不显示的,此时利用第二天的最高温度代替。18 except AttributeError: 19 temperatureHigh = tagToday.find_next('p', class_="tem").span.string #获取第二天的最高温度代替20 21 temperatureLow = tagToday.i.string #获取最低温度22 weather = soup.find('p', class_ = "wea").string #获取天气23 wind = soup.find('p', class_ = "win") #获取风力24 clothes = soup.find('li
