python - 获取一个国家的天气,放置 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()`
解决方案
您可以熟悉 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
表示这些匹配项的列表。您可以按索引访问项目。
推荐阅读
- android - Android 在什么情况下需要用户干预才能发送短信?
- mysql - 基于不同的选择删除
- swift - 将视频上传到 Firebase 存储错误 Swift
- excel - 无法折叠连接到 SSAS 表格模型的数据透视表层次结构
- java - 在 Java Futures 和 Callable 中进行类型检查的通用方法实现
- c - 从宏调用中调用宏
- haskell - Haskell 中的旋转函数
- r - 删除具有 NA 值的特定列
- ios - IOS 拒绝活动指示器在启动时无限旋转,然后在审查时没有产生进一步的行动
- typescript - 在 Typescript 中将嵌套属性访问键入为点字符串