【问题标题】:Python IndexError: no such groupPython IndexError:没有这样的组
【发布时间】:2014-04-24 18:45:39
【问题描述】:

我今天早些时候开始学习 Python,作为我的第一个项目,我想制作一个脚本来显示今天的天气预报。

我的脚本:

import urllib2, re

url = urllib2.urlopen('http://www.wetter.com/wetter_aktuell/wettervorhersage/heute     /deutschland/oberhausen/DE0007740.html')
html = url.read()
url.close()

x = re.search("""<dl><dd><strong>(?P<uhrzeit>.*)""", html, re.S)
x = re.search("""<dd><span class="degreespan" style="font-weight:normal;">(?P<temp>.*)""",  html, re.S)
print x.group('uhrzeit'), x.group('temp')

我使用this 作为模板。当我运行这个脚本时,我得到一个索引错误 no such groups

【问题讨论】:

标签: python html regex


【解决方案1】:

您正在覆盖x

也许你想要:

x = re.search("""<dl><dd><strong>(?P<uhrzeit>.*)""", html, re.S)
y = re.search("""<dd><span class="degreespan" style="font-weight:normal;">(?P<temp>.*)""",  html, re.S)
print x.group('uhrzeit'), y.group('temp')

而且我无法相信您链接的网站提倡使用正则表达式从 HTML 中提取信息。

【讨论】:

  • 使用这个我得到 "AttributeError: "'noneType' Object has no attribute 'group'
  • 那么你的表达式没有找到(匹配)。
  • 真的,不要使用正则表达式来解析 HTML。使用诸如 beautifulsoup 之类的解析器。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-06
  • 1970-01-01
  • 2016-06-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多