Python如何截取特定字符串?

2012-06-14 19:44:53 +08:00
 ihciah
例子:
<html>
<head>
<title>Test</title>
</head>
<body>
<p>输出我</p>
<p>我来捣乱</p>
</body>
</html>

用Pyhton提取其中的'输出我'。输出第一个<p>和第一个</p>之间的内容。

谢谢!!
4892 次点击
所在节点    Google App Engine
13 条回复
INT21H
2012-06-14 19:47:46 +08:00
>>> from BeautifulSoup import BeautifulSoup
>>> html="""<html>
... <head>
... <title>Test</title>
... </head>
... <body>
... <p>输出我</p>
... <p>我来捣乱</p>
... </body>
... </html>"""
>>> bs = BeautifulSoup(html)
>>> bs.p
<p>输出我</p>
>>> bs.p.contents
[u'\u8f93\u51fa\u6211']
>>>
vfasky
2012-06-14 20:56:33 +08:00
<code>
html = '''<html>
<head>
<title>Test</title>
</head>
<body>
<p>输出我</p>
<p>我来捣乱</p>
</body>
</html>'''

for t in html.split('</p>') :
print t.replace('<p>','')
break;
</code>
vfasky
2012-06-14 20:58:41 +08:00
muzuiget
2012-06-14 21:03:12 +08:00
关键词:正则表达式,DOM。
goofansu
2012-06-14 21:05:13 +08:00
最近也在玩,beautifulsoup很棒
yibin001
2012-06-14 21:16:34 +08:00
beautifulsoup还真是个神器
likuku
2012-06-14 21:29:06 +08:00
#!/usr/bin/env python
# encoding: utf-8
"""
html.py

Created by likuku on 2012-06-14.
Copyright (c) 2012 __MyCompanyName__. All rights reserved.
"""

import sys
import os

html="""
<html>
<head>
<title>Test</title>
</head>
<body>
<p>输出我</p>
<p>我来捣乱</p>
</body>
</html>
"""


def main():
for text in html.split('\n'):
if text.find('<p>') != -1:
tmp = text.replace('</p>','').replace('<p>','')
print tmp
break

if __name__ == '__main__':
main()
aa88kk
2012-06-14 21:51:15 +08:00
用正则:
m = re.search('<p>(.*?)<\/p>', s, re.S)
cute
2012-06-14 21:57:50 +08:00
start = s.find('<p>')+ len('<p>')
end = s.find('</p>', start)
print s[start:end]
ihciah
2012-06-14 23:38:09 +08:00
谢谢各位!!~~~~~~~~·
ling0322
2012-06-18 21:46:38 +08:00
其实有一个比beautifulsoap更霸气的, 叫pyQuery
binux
2012-06-18 21:49:04 +08:00
beautifulsoup太费内存了
chairo
2012-06-18 22:25:00 +08:00
libxml路过

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/39509

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX