0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

GetElement example with findall and search in python3

0
Last updated at Posted at 2021-05-16

source

import re

def getElement(src, name, attribute=""):
    e = ""
    print("==findall==")
    ret = re.findall('<'+name+"(>| [^>]+>)([^<]+)<", src, re.S)
    print(ret)
    if ret[0:1]:
        ret = ret[0:1]
        print(ret)
        for i in range(len(ret)):
            print(ret[i])
            print(ret[i][1])
    print("==search==")
    ret = re.search('<'+name+"(>| [^>]+>)([^<]+)<", src, re.S)
    if ret:
        print(ret.group(2))
    else:
        print("could not search")
    #print(ret.groups(),ret.group(1),ret.group(2))

str = """
<span>333</span><a href="/entry" title="タイトル" class=entry-page" label="entry-info"><span>615</span>favs</a>
"""

getElement(str, "span")

result

==findall==
[('>', '333'), ('>', '615')]
[('>', '333')]
('>', '333')
333
==search==
333

memo

  • findallはタプルのリストがかえる。
  • groupを使う場合、if ... is not None を使って判定する。

links

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?