首页 > 解决方案 > 获取一个国家的天气,放置 bs4

问题描述

我正在尝试使用这个网站https://www.timeanddate.com/weather/通过打开一个 URL 来使用 BeautifulSoup4 抓取天气数据:

quote_page=r"https://www.timeanddate.com/weather/%s/%s/ext" %(country, place)

我对网络抓取方法还很陌生BS4,我可以在页面来源中找到我需要的信息(例如,我们在此搜索中将国家设为印度,将城市设为孟买)链接为:https://www. timeanddate.com/weather/india/mumbai/ext

如果您看到页面的来源,不难使用CTRL+F并找到诸如“湿度”、“露点”和当前天气状态(如果晴天、下雨等)等信息的属性,唯一的就是阻止我获取这些数据是我对BS4.

您可以检查页面源并编写BS4获取“感觉”、“能见度”、“露点”、“湿度”、“风”和“预报”等信息的方法吗?

注意:在我必须像<tag class="someclass">value</tag> 使用`

a=BeautifulSoup.find(tag, attrs={'class':'someclass'})
a=a.text.strip()`

标签: pythonweb-scrapingbeautifulsoup

解决方案


您可以熟悉 css 选择器

 import requests
from bs4 import BeautifulSoup as bs
country = 'india'
place = 'mumbai'
headers = {'User-Agent' : 'Mozilla/5.0',
          'Host' : 'www.timeanddate.com'}
quote_page= 'https://www.timeanddate.com/weather/{0}/{1}'.format(country, place) 
res = requests.get(quote_page)
soup = bs(res.content, 'lxml')
firstItem = soup.select_one('#qlook p:nth-of-type(2)')
strings = [string for string in firstItem.stripped_strings]
feelsLike = strings[0]
print(feelsLike)
quickFacts = [item.text for item in soup.select('#qfacts p')]

for fact in quickFacts:
    print(fact)

第一个选择器#qlook p:nth-of-type(2) 使用id 选择器来指定父级,然后使用:nth-of-type CSS 伪类来选择其中的第二个段落类型元素(p 标签)。

该选择器匹配:

在此处输入图像描述

stripped_strings用来分隔各个行并按索引访问所需的信息。


第二个选择器#qfacts p 使用id 选择器作为父元素,然后使用带有类型选择器的后代组合器来指定子 p 标签元素。该组合符合以下条件:p

quickFacts表示这些匹配项的列表。您可以按索引访问项目。


推荐阅读