【问题标题】:attributeError: 'NoneType' object has no attribute 'end'属性错误:“NoneType”对象没有属性“结束”
【发布时间】:2019-03-17 06:39:09
【问题描述】:

我正在为天气预报进行网络抓取。

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

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.end(打印) AttributeError: 'NoneType' 对象没有属性 'end'

【问题讨论】:

  • m = re.search('span class= "phrase"', data1)这个返回None,你应该使用beautifulsoup或其他库来解析网页内容,正则表达式不适合这个东西。
  • 1.检查 data 和 data1 是否为“列表”数据类型。简单地打印它们。 2. 打印“开始”和“结束”变量并验证它们是否包含有效值。

标签: python


【解决方案1】:

刚刚在 Jupyter Online 上进行了测试。这一行给你带来了问题:

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

如果您打印原始 html,您会注意到语法是:

  • span class="短语"

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

Jupyter Test

【讨论】:

  • 感谢您让我知道我的代码中有空格错误。现在我可以运行程序了。
【解决方案2】:

使用BeautifulSoup 遍历/搜索 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.'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-14
    • 2021-02-17
    • 2023-02-17
    • 2018-05-02
    • 1970-01-01
    • 2022-11-29
    • 2021-09-17
    • 2020-10-22
    相关资源
    最近更新 更多