【问题标题】:Python Web-scrapingPython 网页抓取
【发布时间】:2020-12-22 05:46:40
【问题描述】:

当属性与标签中的特定值匹配时,我想返回字符串值。在运行以下代码时,我没有得到任何值。事实上,我想根据“类”属性值“myforecast-current”,“获取所有字符串(即阴霾,39°F,4°C) myforecast-current-lrg”和“myforecast-current-sm”。请帮助正确的代码

if soup.p['class'] == 'myforecast-current-lrg':
   print(soup.p.string)

<div id="current_conditions-summary" class="pull-left" >
                        <img src="newimages/large/ovc.png" alt="" class="pull-left" />
                        <p class="myforecast-current">Overcast with Haze</p>
            <p class="myforecast-current-lrg">39&deg;F</p>
            <p class="myforecast-current-sm">4&deg;C</p>
        </div>

【问题讨论】:

  • 您的代码返回阴霾 39°F 4°C 的阴天。您期望的输出是什么?

标签: python web-scraping beautifulsoup


【解决方案1】:

您必须了解BeautifulSoup 如何查找元素。

这个方法我知道,我觉得应该还有其他方法。

for data in soup.find_all('p', class_='myforecast-current-lrg'):
    print(data.string)

for data in soup.find_all('p'):
    if 'myforecast-current-lrg' in data['class']:
        print(data.string)

【讨论】:

  • 第一个工作,谢谢...另外,如果不同的城市温度是在每次点击时获取的,有没有办法可以从单个 html 文件中提取所有城市的温度,或者我需要获取每个城市的html文件并通过beautifulsoup传递它?希望你有我的问题
  • 一个html文件包含了城市的温度,然后你可以一次得到所有城市的温度。
猜你喜欢
  • 2021-01-12
  • 2022-01-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-20
  • 2023-03-12
  • 2018-04-25
  • 2019-06-18
相关资源
最近更新 更多