Python attributeError:“非类型”对象没有属性“结束”

Python attributeError:“非类型”对象没有属性“结束”,python,Python,我在做天气预报的网页截图 我为这个程序运行的代码是 import re import urllib.request # https://www.weather-forecast.com/locations/Bangalore/forecasts/latest city = input("Enter your city:") url = 'https://www.weather-forecast.com/locations/' + city + '/forecasts/lat

我在做天气预报的网页截图

我为这个程序运行的代码是

import re
import urllib.request
# https://www.weather-forecast.com/locations/Bangalore/forecasts/latest

city = input("Enter your city:")
url = 'https://www.weather-forecast.com/locations/' + city + '/forecasts/latest'

data = urllib.request.urlopen(url).read()

data1 = data.decode('utf-8')


m = re.search('span class= "phrase"', data1)

start = m.end()

end = start + 100

newString = data1[start:end]

print(newString)
我得到以下错误

============================重新启动:C:/Python/weather.py======================= 进入你的城市:西雅图 回溯最近一次呼叫上次: 文件C:/Python/weather.py,第15行,在 开始=m.endprint AttributeError:“非类型”对象没有属性“结束”

用于遍历/搜索HTML等标记文档。它旨在为您省去使用正则表达式解析HTML的麻烦

像这样:

import requests
from bs4 import BeautifulSoup

url = "https://www.weather-forecast.com/locations/Bangalore/forecasts/latest"

data = requests.get(url)
soup = BeautifulSoup(data.text, "lxml")

soup.find("span", {"class": "phrase"}).text
#'Light rain (total 2mm), mostly falling on Sun night. Warm (max 30°C on Sat afternoon, min 20°C on Sat night). Wind will be generally light.'

刚刚在Jupyter Online上测试过。这一行给了你一个问题:

m=重新搜索'span class=phrase',数据1 如果打印原始html,您会注意到语法是:

span class=短语 也就是说,在正则表达式的“=”符号旁边添加一个额外的空格,使其返回None


m=re.search'span class=phrase',data1这将返回None,您应该使用beautifulsoup或其他库来解析网页内容,regex不适合这种情况。1。检查数据和数据1是否为“列表”数据类型。简单地打印它们。2.打印“开始”和“结束”变量,并验证它们是否包含有效值。感谢您让我知道代码中的空格错误。现在我可以运行该程序了。