【问题标题】:how do you extract data from json using beautifulsoup in django你如何在 django 中使用 beautifulsoup 从 json 中提取数据
【发布时间】:2016-02-26 09:40:22
【问题描述】:

美好的一天。我在尝试从 json 中提取值时遇到问题。 首先,我的 beautifulsoup 在 shell 中工作得很好,但在 django 中却不行。而且我想要实现的是从收到的 json 中提取数据,但没有成功。这是我认为这样做的课程:

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 中,有一个数组“Observations”,我试图从中获取城市名称、温度的高低。

但是当我尝试这样做时:

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。那是哪里?
  • 美好的一天,感谢您的回答。代码的这一行 cityDict = json.loads(str(html)) 是在 shell 中完成的,因为我试图访问它。如果成功,那么我可以把它放在 django 中。我试图了解我做错了什么。预期 json 的链接是 stackoverflow.com/questions/35621105/json-data-format-error

标签: json beautifulsoup django-views


【解决方案1】:

request_post.content 中的 JSON 数据有两个问题:

  • 那里有 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

【讨论】:

  • @SlangI'mmatalk 当然,添加了导入语句。
  • 感谢了解日期时间:from django.utils.timezone import datetime.
猜你喜欢
  • 2021-04-24
  • 2019-05-24
  • 1970-01-01
  • 2021-12-01
  • 2019-05-02
  • 1970-01-01
  • 1970-01-01
  • 2021-06-18
  • 2019-06-16
相关资源
最近更新 更多