【问题标题】:Yandex.Weather parsingYandex.天气解析
【发布时间】:2020-01-10 00:01:18
【问题描述】:

我正在尝试从https://www.yandex.com/weather/moscow 下载 7 天预报问题是除了今天之外的所有日子都有相同的班级。如何获得 7 天(或至少 9 天)的预测?

我正在尝试 BeautifulSoap 库。我有今天的天气,但其他日子都是问题。

这是我的代码:

import urllib.request
from bs4 import BeautifulSoup

def get_html(url):
    response = urllib.request.urlopen(url)
    return response.read()

def parse_today(html):
    soup = BeautifulSoup(html, "html.parser")
    temp = soup.find('div', class_='temp fact__temp fact__temp_size_s').get_text().encode('utf-8').decode('utf-8', 'ignore')
    return temp

def parse_next_day(day_num, html):
    # ?????
    pass

def main():
    temp = parse_today(get_html('https://yandex.ru/weather/moscow'))
    print("Now the temperature is: ", temp)
    for i in range(1,6):
        next_temp = parse_next_day(i+1, get_html('https://yandex.ru/weather/moscow'))
        print("The day", i+1, "temperature is : ", next_temp)

if __name__ == '__main__':
    main()

【问题讨论】:

    标签: python-3.x web-scraping html-parsing weather yandex


    【解决方案1】:

    数据是从您可以在网络选项卡中找到的网址动态提取的。它返回 html。您可以使用 css 选择器.card:not(.adv) 隔离预测日期块。 使用 bs4 4.7.1 +。解析出来的例子感觉像临时工:

    import requests
    from bs4 import BeautifulSoup as bs
    
    r = requests.get('https://www.yandex.com/weather/segment/details?offset=0&lat=55.753215&lon=37.622504&geoid=213&limit=10', headers = {'User-Agent':'Mozilla/5.0'})
    soup = bs(r.content, 'lxml')
    
    for card in soup.select('.card:not(.adv)'):
        date = ' '.join([i.text for i in card.select('[class$=number],[class$=month]')])
        print(date)
        temps = list(zip(
                          [i.text for i in card.select('.weather-table__daypart')]
                        , [i.text for i in card.select('.weather-table__body-cell_type_feels-like .temp__value')]
                    ))
        print(temps)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-24
      • 1970-01-01
      • 2013-10-25
      • 2011-12-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多