2016-02-27 59 views
0

现在面对一个奇怪的问题。 我尝试了很多方法,但仍然无法解决问题。 我有以下基于类的视图,它有一个get_context_data()并将处理给定城市的天气。并从返回的JSON我需要提取正确的信息,我想使用,但是,我正在努力使其正确完成。 当我使用django-debug-toolbar检查我的模板上下文呈现时,我能够看到来自json的所有数据,但是当我在浏览器中的实际模板中时,我看到了一些奇怪的事情。 这里是我的代码:使用beautifulsoup和请求提取json数据

class FetchWeather(generic.TemplateView): 
    template_name = 'forecastApp/pages/weather.html' 

    request_post = None 

    def get_context_data(self, **kwargs): 
     context = super().get_context_data(**kwargs) 
     url = 'http://weather.news24.com/sa/cape-town' 
     city = 'cape town' 
     url_request = requests.get(url) 
     soup = BeautifulSoup(url_request.content, 'html.parser') 
     city_list = soup.find(id="ctl00_WeatherContentHolder_ddlCity") 
     print(soup.head) 
     city_as_on_website = city_list.find(text=re.compile(city, re.I)).parent 
     cityId = city_as_on_website['value'] 
     json_url = "http://weather.news24.com/ajaxpro/TwentyFour.Weather.Web.Ajax,App_Code.ashx" 

     headers = { 
      'Content-Type': 'text/plain; charset=UTF-8', 
      'Host': 'weather.news24.com', 
      'Origin': 'http://weather.news24.com', 
      'Referer': url, 
      'User-Agent': 'Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/48.0.2564.82 Chrome/48.0.2564.82 Safari/537.36', 
      'X-AjaxPro-Method': 'GetCurrentOne'} 

     payload = { 
      "cityId": cityId 
     } 
     request_post = requests.post(json_url, headers=headers, data=json.dumps(payload)) 
     print(request_post.content) 
     data = re.sub(r"new Date\(Date\.UTC\((\d+),(\d+),(\d+),(\d+),(\d+),(\d+),(\d+)\)\)", convert_date, request_post.text) 
     data = data.strip(";/*") 
     data = json.loads(data) 
     context["cityId"] = data 
     return context 

,而这些都是实际的模板的屏幕截图,并从DEUG工具栏里的分析: normal template view[![debug toolbar] 2

所以实际上,我只需要形成这样的JSON在预测:

{ 
    'CountryName': 'South Africa', 
    '__type': 'TwentyFour.Services.Weather.Objects.CurrentOneReport, TwentyFour.Services.Weather, Version=1.2.0.0, Culture=neutral, PublicKeyToken=null', 
    'MarineReport': None, 
    'TimeZone': '2', 
    'Location': { 
    '__type': 'TwentyFour.Services.Weather.Objects.Location, TwentyFour.Services.Weather, Version=1.2.0.0, Culture=neutral, PublicKeyToken=null', 
    'Forecasts': [ 
     { 
     'DayLight': 'D', 
     'WindDirection': '161', 
     '__type': 'TwentyFour.Services.Weather.Objects.Forecast, TwentyFour.Services.Weather, Version=1.2.0.0, Culture=neutral, PublicKeyToken=null', 
     'SkyDescriptor': '1', 
     'Date': '2016-01-27T22:00:00', 
     'Rainfall': '*', 
     'Icon': '1', 
     'WindDirectionDescription': 'South', 
     'Visibility': None, 
     'TemperatureDescription': 'Mild', 
     'HighTemp': '24', 
     'TemperatureDescriptor': '8', 
     'BeaufortDescriptor': 'Fresh breeze', 
     'Cached': False, 
     'PrecipitationDescriptor': '', 
     'Snowfall': '*', 
     'DaySegment': None, 
     'ShortWeekDay': 'Sun', 
     'DaySequence': 1, 
     'WindSpeed': '34', 
     'WeekDay': 'Sunday', 
     'Sky': 'Sunny', 
     'PrecipitationProbability': '0', 
     'Precipitation': '', 
     'WindDirectionAbreviated': 'S', 
     'FormattedDate': 'Sun, Feb 28', 
     'Segment': None, 
     'Beaufort': '5', 
     'Description': 'Sunny. Mild.', 
     'IconName': 'sunny', 
     'Temperature': None, 
     'DewPoint': '14', 
     'Air': 'Breezy', 
     'Humidity': '55', 
     'UV': 'High', 
     'Comfort': '25', 
     'LowTemp': '18', 
     'DayOfWeek': 1, 
     'AirDescription': '13' 
     } 
    ], 
    'City': '77107', 
    'Cached': False, 
    'CityName': 'Cape Town' 
    } 

是提取低温,高温和日期,使用beautifulsoup

+3

不完全理解你的问题。如果数据是json格式,为什么你需要BeautifulSoup? –

+0

我有一个非常类似的问题,我改用python鹅代替 – winixxee

+0

也许我使用了错误的方法,但是我希望能够从使用beautifulsoup @warmoverflow后提取的json提取数据 –

回答

1

在我看来,美丽的汤用于检索相关城市的city_id

一旦JSON已经检索它被转换成一个Python对象,具有:

... 
    data = json.loads(data) 
    ... 

假设这正确工作所需的项目可被挑选出来此对象的,并添加到上下文:

EDITED

.... 
    forecast = data['Forecast'] 
    context["LowTemp"] = forecast["LowTemp"] 
    context["HighTemp"] = forecast["HighTemp"] 
    context["Date"] = forecast["Date"] 
    return context 
+0

谢谢我尝试了你的方式,但我有这个错误:文件“/home/drcongo/django_lab/weatherwebapp/src/forecastApp/views.py”,第59行,在get_context_data forecast = data ['cityId' ] ['预测'] –

+0

屏幕截图和粘贴的json之间有一些差异。 '预测=数据''预测''工作吗?屏幕截图没有最后的'预测'。 –

+0

是的,谢谢刚刚删除了['cityId']但仍然对这个场景感到困惑,因为json附带了很多城市,却无法真正了解为什么预测= data ['Forecast']返回了正确的数据在许多城市中没有实际传递所需的城市ID –