[英]Regular expression to return list in Python?
So, I'm wanting to make a list in Python from a large chunk of HTML code, but I'm trying to split it up based on the HTML tags. 因此,我想用大量HTML代码在Python中列出一个列表,但是我试图根据HTML标签对其进行拆分。 I'm not well versed in regular expressions so I don't know how to go about this.
我不熟悉正则表达式,所以我不知道该怎么做。 For instance, let's say I had this piece of HTML code:
例如,假设我有这段HTML代码:
<option value="674"> Example text here </option><option value="673"> Example text here</option><option value="672"> Example text here </option>
I would like for me to be able to save this code (albeit a much bigger version of it) into a string, and then use a function to return a list like this: 我希望能够将这段代码(尽管它的版本更大)保存到字符串中,然后使用一个函数返回如下列表:
list = ["Example text here", "Example text here", "Example text here"]
Anyway I can do this? 反正我能做到吗?
I agree with @roippi's comment, please use HTML parser. 我同意@roippi的评论,请使用HTML解析器。 However, if you really want to use regex, the following is what you want:
但是,如果您确实要使用正则表达式,则需要以下内容:
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']
You could simply use BeautifulSoup
for this purpose. 为此,您可以简单地使用
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')]
Output 产量
['Example text here', 'Example text here', 'Example text here']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.