![](/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.