美好的一天。我在尝试从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)
任何帮助将很乐意赞赏。
你没有定义,你已经证明我们的代码变量'html'。哪里是? – wpercy
美好的一天,感谢您的回答。这行代码cityDict = json.loads(str(html))是在shell中完成的,因为我试图访问它。如果成功,那么我可以把它放在django中。我试图理解我做错了什么。并链接到预期的JSON是http://stackoverflow.com/questions/35621105/json-data-format-error –