![](/img/trans.png)
[英]Return all the occurrences from a string as a list in python using regular expression
[英]Regular expression to return list in Python?
因此,我想用大量HTML代码在Python中列出一个列表,但是我试图根据HTML标签对其进行拆分。 我不熟悉正则表达式,所以我不知道该怎么做。 例如,假设我有这段HTML代码:
<option value="674"> Example text here </option><option value="673"> Example text here</option><option value="672"> Example text here </option>
我希望能够将这段代码(尽管它的版本更大)保存到字符串中,然后使用一个函数返回如下列表:
list = ["Example text here", "Example text here", "Example text here"]
反正我能做到吗?
我同意@roippi的评论,请使用HTML解析器。 但是,如果您确实要使用正则表达式,则需要以下内容:
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']
为此,您可以简单地使用BeautifulSoup
。
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')]
产量
['Example text here', 'Example text here', 'Example text here']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.