如何获得文本组

2024-05-10 04:13:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我是第一次做海报。我正在制作一个程序,通过请求告诉天气,并美化设置正确信息格式的组。我有

import requests
from bs4 import BeautifulSoup

url = 'https://weather.com/en-IN/weather/today/l/91ae3bca47e7dbeb23a6f4b10cb656d234e65f12a1e9b4dc80a0e02e5baa838c'


def getdata(url):
    r = requests.get(url)
    return r.text


htmldata = getdata(
    "https://weather.com/en-IN/weather/today/l/91ae3bca47e7dbeb23a6f4b10cb656d234e65f12a1e9b4dc80a0e02e5baa838c")

soup = BeautifulSoup(htmldata, 'html.parser')

precip = soup.find('div', id='WxuTodayWeatherCard-main-486ce56c-74e0-4152-bd76-7aea8e98520a')

currentPrecip = precip.find('li')

for j in currentPrecip:
    showPrecip = currentPrecip.get_text()

result = f"Current Temp: {showPrecip}"

print(result)

程序正在输出Current Temp: Morning-5°Snow--,我希望它输出Current Temp: -5°C, Sky Snow

如有任何帮助,我们将不胜感激


Tags: inhttpsimport程序comurltodaycurrent
1条回答
网友
1楼 · 发布于 2024-05-10 04:13:36

你的问题不太清楚,你在做预测,并期待当前的数据。这可能需要改进

当前:

live = soup.select_one('div.styles card 3aeCQ a')
print(f"Current Temp: {live.find('span').get_text()}, Sky: {live.find('svg').get_text()}")

预测(上午):

morning = soup.select_one('section[data-testid="TodayWeatherModule"] ul>li')
print(f"Current Temp: {morning.div.span.get_text()}, Sky: {morning.find('title').get_text()}")

示例

import requests
from bs4 import BeautifulSoup

url = 'https://weather.com/en-IN/weather/today/l/91ae3bca47e7dbeb23a6f4b10cb656d234e65f12a1e9b4dc80a0e02e5baa838c'
soup = BeautifulSoup(requests.get(url).text, 'html.parser')

live = soup.select_one('div.styles card 3aeCQ a')
print(f"Current Temp: {live.find('span').get_text()}, Sky: {live.find('svg').get_text()}")

morning = soup.select_one('section[data-testid="TodayWeatherModule"] ul>li')
print(f"Current Temp: {morning.div.span.get_text()}, Sky: {morning.find('title').get_text()}")

输出

Current Temp: -2°, Sky: Snow
Current Temp: -5°, Sky: Snow

相关问题 更多 >