【问题标题】:Python Regular Expression WebpagePython 正则表达式网页
【发布时间】:2014-02-02 09:47:02
【问题描述】:

我需要帮助为网页编写正则表达式以提取一些数据。网页是: http://www.city-data.com/city/Addison-Texas.html

我想从这段 html 代码中返回“达拉斯”:

<a href="/county/Dallas_County-TX.html">Dallas County</a>
</p>
<b>Population in 2012:</b>

这是我到目前为止写的正则表达式,但它似乎不起作用。知道我做错了什么吗?

(">(.)/sCounty</a>\n</p>\n<b>Population in 2012:</b>")

【问题讨论】:

  • 空格不是/s,而是\s
  • 我仍然收到同样的错误:Traceback (last last call last): File "", line 1, in IndexError: list index out of range
  • 采取this question中的解决方案之一。您不想在 HTML 上使用正则表达式,因为正则表达式无法解析 HTML
  • 秘诀是永远不要使用正则表达式来解析 html。 stackoverflow.com/questions/1732348/…
  • (.) 匹配单个字符。

标签: python html regex


【解决方案1】:

好吧,解决它的另一种方法是使用split函数,而不是使用regex

s.split('</a>')[0].split('>')[1].split(' ')[0]

应该返回你想要的答案。

但是,对于更复杂的 HTML,使用上述方法变得乏味。您可以改用HTMLParser 模块。

【讨论】:

  • +1 当有人要求使用 html 正则表达式时,唯一正确的答案是告诉他们停止对 html 使用正则表达式。
猜你喜欢
  • 2020-09-28
  • 2014-10-23
  • 1970-01-01
  • 2023-04-09
  • 1970-01-01
  • 1970-01-01
  • 2013-07-30
  • 1970-01-01
  • 2010-09-12
相关资源
最近更新 更多