【问题标题】:Scrape <div<span from HTML-page从 HTML 页面中抓取 <div<span
【发布时间】:2021-06-09 21:34:53
【问题描述】:

我正在尝试在 Eclipse 中使用 Python 创建一个简单的天气预报。到目前为止,我已经写了这个:

from bs4 import BeautifulSoup
import requests


def weather_forecast():
    url = 'https://www.yr.no/nb/v%C3%A6rvarsel/daglig-tabell/1-92416/Norge/Vestland/Bergen/Bergen'
    r = requests.get(url)  # Get request for contents of the page
    print(r.content)  # Outputs HTML code for the page
    soup = BeautifulSoup(r.content, 'html5lib')  # Parse the data with BeautifulSoup(HTML-string, html-parser)
    min_max = soup.select('min-max.temperature')  # Select all spans with a "min-max-temperature" attribute
    print(min_max.prettify())
    table = soup.find('div', attrs={'daily-weather-list-item__temperature'})
    print(table.prettify())
   

来自具有如下元素的 html 页面:

我在 HTML 页面的元素中找到了第一个温度的路径,但是当我尝试执行我的代码并打印以查看我是否正确完成时,没有打印任何内容。我的目标是打印一个包含日期和相​​应温度的表格,这似乎是一项简单的任务,但我不知道如何正确命名属性或如何在一次迭代中从 HTML 页面中将它们全部刮掉。

我想进入每个

我在 stackoverflow 上看过这个问题,但我想不通: Python BeautifulSoup - Scraping Div Spans and p tags - also how to get exact match on div name

【问题讨论】:

  • 如果代码附加了脚本标签,那么 bs4 有一半的时间不能工作。如果是这种情况,您将不得不使用 selenium 之类的东西。

标签: python html web-scraping beautifulsoup


【解决方案1】:

您可以使用字典理解。遍历所有具有daily-weather-list-item类的预测,然后从时间标签的datetime属性中提取日期,并将其用作键;将键与 maxmin 信息相关联。

import requests
from bs4 import BeautifulSoup

def weather_forecast():
    url = 'https://www.yr.no/nb/v%C3%A6rvarsel/daglig-tabell/1-92416/Norge/Vestland/Bergen/Bergen'
    r = requests.get(url)  # Get request for contents of the page
    soup = BeautifulSoup(r.content, 'html5lib')  
    temps = {i.select_one('time')['datetime']:i.select_one('.min-max-temperature').get_text(strip= True) 
             for i in soup.select('.daily-weather-list-item')}
    return temps

weather_forecast()

【讨论】:

    猜你喜欢
    • 2023-04-04
    • 1970-01-01
    • 2018-03-20
    • 1970-01-01
    • 1970-01-01
    • 2012-11-24
    • 2015-04-05
    • 1970-01-01
    相关资源
    最近更新 更多