akjasim / cb_dj_weather_app

Django Weather App
13 stars 10 forks source link

AttributeError: 'NoneType' object has no attribute 'text' #1

Open mrpal39 opened 3 years ago

mrpal39 commented 3 years ago

response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/rudi/devs/projects/blog/views.py", line 54, in project result['region'] = soup.find("div", attrs={"id": "wob_loc"}).text AttributeError: 'NoneType' object has no attribute 'text' [20/Dec/2020 11:52:01] "GET /project/?city=phraral HTTP/1.1" 500 79073

neethukbj commented 6 months ago

It seems that the issue is occurring when trying to access the .text attribute on the results from soup.find() calls. This error occurs when the soup.find() method does not find the specified HTML element, and it returns None. Trying to access the .text attribute on None results in the "NoneType object has no attribute 'text'" error.

To avoid this issue, you should check if the element is found before trying to access its .text attribute. You can use an if statement to ensure that the element is not None before trying to access its text content. Here's an updated version of your code: def HOME(request): weather = None if 'city' in request.GET:

Fetch weather data

    city = request.GET['city']
    html_content = get_html_content(city)
    from bs4 import BeautifulSoup
    weather = dict()
    soup = BeautifulSoup(html_content, 'html.parser')

    region_element = soup.find('span', attrs={'class': 'BBwThe'})
    dayhour_element = soup.find('div', attrs={'id': 'wob_dts'})
    status_element = soup.find('span', attrs={'id': 'wob_dc'})
    temp_element = soup.find('span', attrs={'id': 'wob_tm'})

    # Check if elements are found before accessing their text content
    if region_element:
        weather['region'] = region_element.text
    if dayhour_element:
        weather['dayhour'] = dayhour_element.text
    if status_element:
        weather['status'] = status_element.text
    if temp_element:
        weather['temp'] = temp_element.text
    print(weather)

return render(request, 'home.html', {'weather': weather})