2016-02-26 61 views
1

美好的一天。我在嘗試從json中提取值時遇到了一個問題。 首先,我的beautifulsoup在shell中工作得很好,但在django中卻沒有。而且我試圖實現的是從接收的json中提取數據,但沒有成功。下面是在我看來,類做:你如何從json中提取數據使用django中的beautifulsoup

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

    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) 
     context['Observations'] = request_post.content 
     return context 

在JSON,有一個數組「意見」從我試圖讓城市名稱,溫度高和低。

但是當我試圖做到這一點:

cityDict = json.loads(str(html)) 

我收到一個錯誤。這是它的追溯:

Traceback (most recent call last): 
    File "<console>", line 1, in <module> 
    File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/json/__init__.py", line 319, in loads 
    return _default_decoder.decode(s) 
    File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/json/decoder.py", line 339, in decode 
    obj, end = self.raw_decode(s, idx=_w(s, 0).end()) 
    File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/json/decoder.py", line 357, in raw_decode 
    raise JSONDecodeError("Expecting value", s, err.value) from None 
json.decoder.JSONDecodeError: Expecting value: line 1 column 4067 (char 4066) 

任何幫助將很樂意讚賞。

+0

你沒有定義,你已經證明我們的代碼變量'html'。哪裏是? – wpercy

+0

美好的一天,感謝您的回答。這行代碼cityDict = json.loads(str(html))是在shell中完成的,因爲我試圖訪問它。如果成功,那麼我可以把它放在django中。我試圖理解我做錯了什麼。並鏈接到預期的JSON是http://stackoverflow.com/questions/35621105/json-data-format-error –

回答

1

有兩個問題與你的JSON數據中request_post.content

  • 有JS日期對象的值出現,例如:

    "Date":new Date(Date.UTC(2016,1,26,22,0,0,0)) 
    
  • 有在最後不想要的字符:;/*"

讓我們清理JSON數據,以便它可以與json加載:

from datetime import datetime 

data = request_post.text 

def convert_date(match): 
    return '"' + datetime(*map(int, match.groups())).strftime("%Y-%m-%dT%H:%M:%S") + '"' 

data = re.sub(r"new Date\(Date\.UTC\((\d+),(\d+),(\d+),(\d+),(\d+),(\d+),(\d+)\)\)", 
       convert_date, 
       data) 

data = data.strip(";/*") 
data = json.loads(data) 

context['Observations'] = data 
+0

@ SlangI'mmatalk肯定,添加了一個導入語句。 – alecxe

+0

感謝關於日期時間:從django.utils.timezone導入日期時間。 –

相關問題