Spaces:
Runtime error
Runtime error
| import gradio as gr | |
| import requests | |
| from bs4 import BeautifulSoup | |
| # Function to fetch and scrape weather data from a public website | |
| def get_weather_from_web(query): | |
| try: | |
| # Use the query to construct the search URL, e.g., search weather in Lahore | |
| search_url = f"https://www.google.com/search?q=weather+in+{query}" | |
| # Send a GET request to fetch the web page | |
| headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36"} | |
| response = requests.get(search_url, headers=headers) | |
| # If the request was successful, parse the HTML content | |
| if response.status_code == 200: | |
| soup = BeautifulSoup(response.text, 'html.parser') | |
| # Find the weather information in the page content | |
| weather_info = soup.find("div", {"class": "BNeawe iBp4i AP7Wnd"}) | |
| temperature = weather_info.text if weather_info else "Weather data not found." | |
| # Extract the condition of the weather | |
| condition_info = soup.find("div", {"class": "BNeawe tAd8D AP7Wnd"}) | |
| condition = condition_info.text if condition_info else "Condition data not found." | |
| # Return the formatted weather information | |
| weather_report = f"Temperature: {temperature}\nCondition: {condition}" | |
| return weather_report | |
| else: | |
| return "Error: Unable to fetch data." | |
| except Exception as e: | |
| return f"Error: {str(e)}" | |
| # Create a Gradio interface | |
| def main(): | |
| with gr.Blocks() as demo: | |
| gr.Markdown("# Weather Search App") | |
| gr.Markdown("### Enter a city to get the current weather (without API key).") | |
| # Textbox for user input | |
| query_input = gr.Textbox(label="Search City (e.g., Lahore)", value="Lahore", interactive=True) | |
| # Textbox to display the result | |
| result_output = gr.Textbox(label="Weather Info", interactive=False) | |
| # Trigger the search on submit | |
| query_input.submit(get_weather_from_web, inputs=query_input, outputs=result_output) | |
| demo.launch() | |
| if __name__ == "__main__": | |
| main() |