[英]Python regular expression for multiple tags
我想知道如何從每個<p>
標簽中檢索所有結果。
import re
htmlText = '<p data="5" size="4">item1</p><p size="4">item2</p><p size="4">item3</p>'
print re.match('<p[^>]*size="[0-9]">(.*?)</p>', htmlText).groups()
結果:
('item1', )
我需要的:
('item1', 'item2', 'item3')
對於此類問題,建議使用DOM解析器,而不是正則表達式。
我見過經常推薦用於Python的Beautiful Soup
美麗的湯肯定是這樣的問題的方式。 代碼更清晰,更易於閱讀。 安裝完成后,獲取所有標簽就像這樣。
from BeautifulSoup import BeautifulSoup
import urllib2
def getTags(tag):
f = urllib2.urlopen("http://cnn.com")
soup = BeautifulSoup(f.read())
return soup.findAll(tag)
if __name__ == '__main__':
tags = getTags('p')
for tag in tags: print(tag.contents)
這將打印出p標簽的所有值。
正則表達式的答案非常脆弱。 這是證明(以及一個有效的BeautifulSoup示例)。
from BeautifulSoup import BeautifulSoup
# Here's your HTML
html = '<p data="5" size="4">item1</p><p size="4">item2</p><p size="4">item3</p>'
# Here's some simple HTML that breaks your accepted
# answer, but doesn't break BeautifulSoup.
# For each example, the regex will ignore the first <p> tag.
html2 = '<p size="4" data="5">item1</p><p size="4">item2</p><p size="4">item3</p>'
html3 = '<p data="5" size="4" >item1</p><p size="4">item2</p><p size="4">item3</p>'
html4 = '<p data="5" size="12">item1</p><p size="4">item2</p><p size="4">item3</p>'
# This BeautifulSoup code works for all the examples.
paragraphs = BeautifulSoup(html).findAll('p')
items = [''.join(p.findAll(text=True)) for p in paragraphs]
使用BeautifulSoup。
您可以像這樣使用re.findall
:
import re
html = '<p data="5" size="4">item1</p><p size="4">item2</p><p size="4">item3</p>'
print re.findall('<p[^>]*size="[0-9]">(.*?)</p>', html)
# This prints: ['item1', 'item2', 'item3']
編輯 :...但正如許多評論者指出的那樣,使用正則表達式解析HTML通常是一個壞主意。
或者, xml.dom.minidom將解析您的HTML,如果,
例如,
>>> import xml.dom.minidom
>>> htmlText = '<p data="5" size="4">item1</p><p size="4">item2</p><p size="4">item3</p>'
>>> d = xml.dom.minidom.parseString('<not_p>%s</not_p>' % htmlText)
>>> tuple(map(lambda e: e.firstChild.wholeText, d.firstChild.childNodes))
('item1', 'item2', 'item3')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.