我想使用re
模塊從一個字符串中提取所有的html節點,包括所有的attrs。但是,我希望每個屬性都是一個組,這意味着我可以使用matchobj.group()
來獲取它們。節點中attrs的數量是柔性的。這是我困惑的地方。我不知道如何編寫這樣的正則表達式。我試過</?(\w+)(\s\w+[^>]*?)*/?>'
,但對於像<a href='aaa' style='bbb'>
這樣的節點,我只能得到[('a'), ('style="bbb")]
這兩個組。
我知道有一些很好的HTML解析器。但實際上我不會提取attrs的價值。我需要修改原始字符串。使用正則表達式來提取所有html attrs
回答
說明
要捕捉屬性的無限數量也將需要兩個步驟,你拉其中第一整個元素。然後你遍歷元素並獲得一組匹配的屬性。
正則表達式來抓住所有的元素:<\w+(?=\s|>)(?:[^>=]|='[^']*'|="[^"]*"|=[^'"][^\s>]*)*?>
正則表達式抓住所有從單個元素的屬性:\s\w+=(?:'[^']*'|"[^"]*"|[^'"][^\s>]*)(?=\s|>)
Python的實施例
查看工作例如:http://repl.it/J0t/4
代碼
import re
string = """
<a href="i.like.kittens.com" NotRealAttribute=' true="4>2"' class=Fonzie>text</a>
""";
for matchElementObj in re.finditer(r'<\w+(?=\s|>)(?:[^>=]|=\'[^\']*\'|="[^"]*"|=[^\'"][^\s>]*)*?>', string, re.M|re.I|re.S):
print "-------"
print "matchElementObj.group(0) : ", matchElementObj.group(0)
for matchAttributesObj in re.finditer(r'\s\w+=(?:\'[^\']*\'|"[^"]*"|[^\'"][^\s>]*)(?=\s|>)', string, re.M|re.I|re.S):
print "matchAttributesObj.group(0) : ", matchAttributesObj.group(0)
輸出
-------
matchElementObj.group(0) : <a href="i.like.kittens.com" NotRealAttribute=' true="4>2"' class=Fonzie>
matchAttributesObj.group(0) : href="i.like.kittens.com"
matchAttributesObj.group(0) : NotRealAttribute=' true="4>2"'
matchAttributesObj.group(0) : class=Fonzie
Please don't use regex。使用BeautifulSoup
:
>>> from bs4 import BeautifulSoup as BS
>>> html = """<a href='aaa' style='bbb'>"""
>>> soup = BS(html)
>>> mytag = soup.find('a')
>>> print mytag['href']
aaa
>>> print mytag['style']
bbb
或者,如果你想要一本字典:
>>> print mytag.attrs
{'style': 'bbb', 'href': 'aaa'}
我知道HTML解析器應該是很好的選擇,但實際上我不認爲它們可以爲我工作。我需要修改原始字符串。 – zhangyangyu
@zhangyangyu看看[這個](http://www.crummy.com/software/BeautifulSoup/bs4/doc/#replace-with)也許 – TerryA
請問downvoter請澄清他們爲什麼downvoted – TerryA
- 1. 正則表達式來提取HTML值
- 2. 提取所有與正則表達式
- 3. 提取所有html標記,並用正則表達式關閉
- 4. 正則表達式提取HTML正文
- 5. 使用正則表達式來提取所需的數據
- 6. 正則表達式提取所有圖像和HTML
- 7. 正則表達式來提取所有重複字符
- 8. 正則表達式HTML提取C#
- 9. PHP正則表達式HTML - 提取URL
- 10. PHP正則表達式提取html值
- 11. 使用正則表達式來獲取所有屬性
- 12. 正則表達式來提取和URL
- 13. 正則表達式來提取URL
- 14. 正則表達式來提取值
- 15. 正則表達式來提取
- 16. 正則表達式來提取主機
- 17. 正則表達式來提取數據
- 18. 正則表達式來提取URL
- 19. 正則表達式來提取數
- 20. 正則表達式來提取值
- 21. Java的正則表達式來提取
- 22. 正則表達式來提取href url
- 23. 正則表達式來提取鳴叫
- 24. 正則表達式來提取段落
- 25. 提取使用正則表達式
- 26. 使用正則表達式提取值
- 27. 使用正則表達式提取域
- 28. 提取使用正則表達式
- 29. 值提取使用正則表達式
- 30. 使用正則表達式提取值
FFS ... http://www.crummy.com/software/BeautifulSoup/ –
考慮使用HTML解析器代替正則表達式。 http://www.crummy.com/software/BeautifulSoup/ – Achrome
正常第一場比賽被第二場比賽覆蓋。 –