Python正则表达式切片

2024-04-23 15:25:41 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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”。你知道吗


Tags: 代码fromdiv网页示例messagestringtype
2条回答

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

不要被名字拖后腿-这是一个严肃的模块,被很多人用得很成功。documentation page有很多例子可以帮助您开始了解您的特殊需求。你知道吗

你为什么不试试用BeautifulSoup

示例代码:

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

相关问题 更多 >