我正在尝试使用此网站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>
获取HTML标记中的值。
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 selector指定父级,然后使用:nth-of-type CSS pseudo-class来选择第二个段落类型元素(p标签)。
该选择器匹配:
我使用stripped_strings
来分离各个行并通过索引访问所需的信息。
第二个选择器#qfacts p
使用id selector作为父元素,然后使用descendant combinator和p
type selector来指定子p标签元素。该组合符合以下条件:
quickFacts
代表这些比赛的清单。您可以按索引访问项目。