【问题标题】:Python /bs4: trying to print temperature/city from a local websitePython /bs4:尝试从本地网站打印温度/城市
【发布时间】:2017-06-30 13:22:08
【问题描述】:

我正在尝试从本地网站获取并打印当前的天气温度和城市名称,但没有成功。 我只需要它来读取和打印城市(Lodrina)、温度(23.1C)以及可能的话 ca-cond-firs 中的标题(“Temperatura em declínio”)——最后一个会随着温度的升高或降低而变化。 ..

这是网站的 html 部分:

THIS IS THE HTML (the part of matters:)
#<div class="ca-cidade"><a href="/site/internas/conteudo/meteorologia/grafico.shtml?id=23185109">Londrina</a></div>
<ul class="ca-condicoes">
<li class="ca-cond-firs"><img src="/site/imagens/icones_condicoes/temperatura/temp_baixa.png" title="Temperatura em declínio"/><br/>23.1°C</li>
<li class="ca-cond"><img src="/site/imagens/icones_condicoes/vento/L.png"/><br/>10 km/h</li>
<li class="ca-cond"><div class="ur">UR</div><br/>54%</li>
<li class="ca-cond"><img src="/site/imagens/icones_condicoes/chuva.png"/><br/>0.0 mm</li>

这是我到目前为止所做的代码:

from bs4 import BeautifulSoup
import requests

URL = 'http://www.simepar.br/site/index.shtml'

rawhtml = requests.get(URL).text
soup = BeautifulSoup(rawhtml, 'lxml')

id = soup.find('a', 'id=23185109')
print(id)

有什么帮助吗?

【问题讨论】:

    标签: python parsing bs4


    【解决方案1】:
    from bs4 import BeautifulSoup
    import requests
    
    URL = 'http://www.simepar.br/site/index.shtml'
    
    rawhtml = requests.get(URL).text
    soup = BeautifulSoup(rawhtml, 'html.parser') # parse page as html
    
    temp_table = soup.find_all('table', {'class':'cidadeTempo'}) # get detail of table with class name cidadeTempo
    for entity in temp_table:
        city_name = entity.find('h3').text # fetches name of city
        city_temp_max = entity.find('span', {'class':'tempMax'}).text # fetches max temperature
        city_temp_min = entity.find('span', {'class':'tempMin'}).text # fetches min temperature
        print("City :{} \t Max_temp: {} \t Min_temp: {}".format(city_name, city_temp_max, city_temp_min)) # prints content
    

    下面的代码可以根据需要在页面右侧获取温度的详细信息。

    result_table = soup.find('div', {'class':'ca-content-wrapper'})
    print(result_table.text) # in your case there is no other div exist with class name ca-content-wrapper hence I can use it directly without iterating. you can use if condition to control which city temprature to print and which to not.
        # output will be like :
            # Apucarana
    
            # 21.5°C
            # 4 km/h
            # UR60%
            # 0.0 mm
    

    【讨论】:

    • 哦,city_name 的编码错误 - 您可能希望在打印时将其替换为 bytes(city_name, encoding='latin1').decode('utf-8')
    • 您的代码工作正常,但它可以预测当天的最低/最高温度。我需要当前值(延迟 15 分钟)。如果您看到 www.simepar.br,它就是该站点的正确部分。城市是隆德里纳。
    【解决方案2】:

    我不确定您的代码遇到了什么问题。在尝试使用您的代码时,我发现我需要使用 html 解析器才能成功解析网站。我还使用了 soup.findAll() 来查找与所需类匹配的元素。希望以下内容能引导您找到答案:

    from bs4 import BeautifulSoup
    import requests
    
    URL = 'http://www.simepar.br/site/index.shtml'
    
    rawhtml = requests.get(URL).text
    soup = BeautifulSoup(rawhtml, 'html.parser')
    
    rows = soup.findAll('li', {'class', 'ca-cond-firs'})
    print rows
    

    【讨论】:

      【解决方案3】:

      你应该试试 BS4 中的 CSS3 选择器,我个人觉得它比 find 和 find_all 更容易使用。

      from bs4 import BeautifulSoup
      import requests
      
      URL = 'http://www.simepar.br/site/index.shtml'
      
      rawhtml = requests.get(URL).text
      soup = BeautifulSoup(rawhtml, 'lxml')
      
      # soup.select returns the list of all the elements that matches the CSS3 selector
      
      # get the text inside each <a> tag inside div.ca-cidade
      cities = [cityTag.text for cityTag in soup.select("div.ca-cidade > a")] 
      
      # get the temperature inside each li.ca-cond-firs
      temps = [tempTag.text for tempTag in soup.select("li.ca-cond-firs")]
      
      # get the temperature status inside each li.ca-cond-firs > img title attibute
      tempStatus = [tag["title"] for tag in soup.select("li.ca-cond-firs > img")]
      
      # len(cities) == len(temps) == len(tempStatus) => This is normally true.
      
      for i in range(len(cities)):
          print("City: {}, Temperature: {}, Status: {}.".format(cities[i], temps[i], tempStatus[i]))
      

      【讨论】:

      • 太棒了!像cham一样工作!你能告诉我我应该怎么做才能只打印一个孤立的城市(如果我想的话)?
      • 你可以试试这个,如果你知道你要找的城市在城市列表中:print("City: {}, Temperature: {}, Status: {}.".format(cities[cities.index("Londrina")], temps[cities.index("Londrina")], tempStatus[cities.index("Londrina")]))
      【解决方案4】:

      给你。您可以根据图标名称自定义风的东西。

      #!/usr/bin/env python
      # -*- encoding: utf8 -*-
      import sys
      
      reload(sys)
      sys.setdefaultencoding('utf-8')
      
      from bs4 import BeautifulSoup
      import requests
      
      def get_weather_data():
      
          URL = 'http://www.simepar.br/site/index.shtml'
      
          rawhtml = requests.get(URL).text
          soup = BeautifulSoup(rawhtml, 'html.parser')
      
          cities = soup.find('div', {"class":"ca-content-wrapper"})
      
          weather_data = []
      
          for city in cities.findAll("div", {"class":"ca-bg"}):
      
              name = city.find("div", {"class":"ca-cidade"}).text
              temp = city.find("li", {"class":"ca-cond-firs"}).text
      
              conditons = city.findAll("li", {"class":"ca-cond"})
      
              weather_data.append({
                  "city":name,
                  "temp":temp,
                  "conditions":[{
                      "wind":conditons[0].text +" "+what_wind(conditons[0].find("img")["src"]),
                      "humidity":conditons[1].text,
                      "raind":conditons[2].text,
                  }]
              })
      
      
          return weather_data
      
      def what_wind(img):
          if img.find ("NE"):
              return "From North East"
      
          if img.find ("O"):
              return "From West"
      
          if img.find ("N"):
              return "From North"
      
          #you can add other icons here
      
      
      print get_weather_data()
      

      这是来自该网站的所有天气数据。

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-07
      • 2015-09-04
      • 1970-01-01
      • 1970-01-01
      • 2014-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多