【问题标题】:Python regular expression slicingPython正则表达式切片
【发布时间】:2010-09-25 05:40:47
【问题描述】:

我正在尝试使用以下示例代码获取网页:

from urllib import urlopen
print urlopen("http://www.php.net/manual/en/function.gettext.php").read()

现在我可以在一个变量中获取整个网页。我想要页面的一部分包含这样的内容

<div class="methodsynopsis dc-description">
   <span class="type">string</span><span class="methodname"><b>gettext</b></span> ( <span class="methodparam"><span class="type">string</span> <tt class="parameter">$message</tt></span>
   )</div>

这样我就可以生成一个文件以在另一个应用程序中实现。 我希望能够提取单词“string”、“gettext”和“$message”。

【问题讨论】:

标签: python html regex


【解决方案1】:

你为什么不试试 BeautifulSoup

示例代码:

from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup(htmldoc)
allSpans = soup.findAll('span', class="type")
for element in allSpans:
    ....

【讨论】:

    【解决方案2】:

    从 HTML 中提取信息时,不建议将一些正则表达式组合在一起。 正确的 方法是使用适当的 HTML 解析模块。为此,Python 有几个很好的模块——我特别推荐BeautifulSoup

    不要被这个名字吓到 - 这是一个被很多人使用并取得巨大成功的严肃模块。 documentation page 有很多示例可以帮助您开始满足您的特定需求。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-29
      • 2010-09-12
      • 2011-08-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多