在Python中返回列表的正则表达式?

2024-04-18 10:06:12 发布

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

所以,我想用Python从一大块HTML代码中创建一个列表,但是我试图根据HTML标记将其拆分。我不太精通正则表达式,所以不知道该怎么做。例如,假设我有一段HTML代码:

<option value="674"> Example text here </option><option value="673"> Example text here</option><option value="672"> Example text here </option>

我希望我能够将这段代码(尽管它的版本要大得多)保存到字符串中,然后使用函数返回如下列表:

^{pr2}$

不管怎样,我能做到吗?在


Tags: 函数字符串代码text标记版本列表here
2条回答

我同意@roippi的评论,请使用HTML解析器。但是,如果您真的想使用regex,则需要以下内容:

import re

s = '<option value="674"> Example text here </option><option value="673"> Example text here</option><option value="672"> Example text here </option>'

>>> print re.findall(r'>\s*([^<]+?)\s*<', s)
['Example text here', 'Example text here', 'Example text here']

您可以简单地使用^{}来实现这个目的。在

import bs4

html = '''
<option value="674"> Example text here </option>
<option value="673"> Example text here</option>
<option value="672"> Example text here </option>
'''

soup  = bs4.BeautifulSoup(html)
mylst = [str(x.text).strip() for x in soup.find_all('option')]

输出

^{pr2}$

相关问题 更多 >