我正在编写一个程序,该程序使用beautifulsoup
解析weather.com站点并打印天气。当解析要打印的位置时,会打印一个不需要的单词:
今天在不列颠哥伦比亚省的伯纳比天气,外面的天气部分多云,为10°
不列颠哥伦比亚省之后的"Weather"是不受欢迎的。如何从课堂上只抓取部分文本?
相关代码:
current_temperature = soup.find(class_="CurrentConditions--tempValue--3KcTQ").text
current_state = soup.find(class_="CurrentConditions--phraseValue--2xXSr").text
current_location = soup.find(class_="CurrentConditions--location--1Ayv3").text
string = "nToday in " + current_location + ", the weather outside is " + current_state + ", at " + current_temperature + "n"
print(string)
完整输出:
今天在不列颠哥伦比亚省的伯纳比天气,外面的天气部分多云,为10°
提前感谢的帮助
如果这种情况很常见,您可以尝试一种暴力方法:
current_location = soup.find(class_="CurrentConditions--location--1Ayv3").text
current_location = current_location[:current_location.find(" Weather")]
x = string.replace('Weather ','')
print(x)
最方便的方法是用一个";。
string.replace(" Weather", "")
记住在Weather之前添加一个空格,因为你不需要这个空格。