DAOCLOUD
推荐学习书目
› Python Cookbook
› Using Google App Engine
推荐下载
› Latest Google App Engine SDK
其他兼容技术
› AppScale
ihciah
0.2D
0.03D

Python如何截取特定字符串?

  •  
  •   ihciah · Jun 14, 2012 · 5996 views
    This topic created in 5265 days ago, the information mentioned may be changed or developed.
    例子:
    <html>
    <head>
    <title>Test</title>
    </head>
    <body>
    <p>输出我</p>
    <p>我来捣乱</p>
    </body>
    </html>

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

    谢谢!!
    13 replies  •  1970-01-01 08:00:00 +08:00
    INT21H
    INT21H
    Jun 14, 2012❤️1
    1
    >>> 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
    vfasky
    Jun 14, 2012
    2
    <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>
    muzuiget
    muzuiget
    Jun 14, 2012
    4
    关键词:正则表达式,DOM。
    goofansu
    goofansu
    Jun 14, 2012
    5
    最近也在玩,beautifulsoup很棒
    celloyee
    celloyee
    Jun 14, 2012
    6
    beautifulsoup还真是个神器
    likuku
    likuku
    Jun 14, 2012❤️1
    7
    #!/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
    aa88kk
    Jun 14, 2012❤️1
    8
    用正则:
    m = re.search('<p>(.*?)<\/p>', s, re.S)
    cute
    cute
    Jun 14, 2012❤️1
    9
    start = s.find('<p>')+ len('<p>')
    end = s.find('</p>', start)
    print s[start:end]
    ihciah
    ihciah
    OP
    Jun 14, 2012
    10
    谢谢各位!!~~~~~~~~·
    ling0322
    ling0322
    Jun 18, 2012
    11
    其实有一个比beautifulsoap更霸气的, 叫pyQuery
    binux
    binux
    Jun 18, 2012
    12
    beautifulsoup太费内存了
    chairo
    chairo
    Jun 18, 2012
    13
    libxml路过
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   1924 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 43ms · UTC 01:03 · PVG 09:03 · LAX 17:03 · JFK 20:03
    ♥ Do have faith in what you're doing.