pythonpython-3.xbeautifulsoupoutputoutput-formatting

How to just get text BeautifulSoup


I am a first time poster. I'm making a program to tell the weather with requests and BeautifulSoup that is formatting the proper information wrong. I have

import requests
from bs4 import BeautifulSoup

url = 'https://weather.com/en-IN/weather/today/l/91ae3bca47e7dbeb23a6f4b10cb656d234e65f12a1e9b4dc80a0e02e5baa838c'


def getdata(url):
    r = requests.get(url)
    return r.text


htmldata = getdata(
    "https://weather.com/en-IN/weather/today/l/91ae3bca47e7dbeb23a6f4b10cb656d234e65f12a1e9b4dc80a0e02e5baa838c")

soup = BeautifulSoup(htmldata, 'html.parser')

precip = soup.find('div', id='WxuTodayWeatherCard-main-486ce56c-74e0-4152-bd76-7aea8e98520a')

currentPrecip = precip.find('li')

for j in currentPrecip:
    showPrecip = currentPrecip.get_text()

result = f"Current Temp: {showPrecip}"

print(result)

The program is outputting Current Temp: Morning-5°Snow-- and I want it to output Current Temp: -5°C, Sky Snow

Any help is appreciated and thanks in advance


Solution

  • Your question is not that clear, your taking the forecast and expect the current data. This may should be improved.

    Current:

    live = soup.select_one('div.styles--card--3aeCQ a')
    print(f"Current Temp: {live.find('span').get_text()}, Sky: {live.find('svg').get_text()}")
    

    Forecast (Morning):

    morning = soup.select_one('section[data-testid="TodayWeatherModule"] ul>li')
    print(f"Current Temp: {morning.div.span.get_text()}, Sky: {morning.find('title').get_text()}")
    

    Example

    import requests
    from bs4 import BeautifulSoup
    
    url = 'https://weather.com/en-IN/weather/today/l/91ae3bca47e7dbeb23a6f4b10cb656d234e65f12a1e9b4dc80a0e02e5baa838c'
    soup = BeautifulSoup(requests.get(url).text, 'html.parser')
    
    live = soup.select_one('div.styles--card--3aeCQ a')
    print(f"Current Temp: {live.find('span').get_text()}, Sky: {live.find('svg').get_text()}")
    
    morning = soup.select_one('section[data-testid="TodayWeatherModule"] ul>li')
    print(f"Current Temp: {morning.div.span.get_text()}, Sky: {morning.find('title').get_text()}")
    

    Output

    Current Temp: -2°, Sky: Snow
    Current Temp: -5°, Sky: Snow