繁体   English   中英

在python正则表达式中匹配多行

[英]matching multiple line in python regular expression

我想从html页面中提取<tr>标签之间的数据。 我使用了以下代码。但我没有得到任何结果。 <tr>标签之间的html是多行的

category =re.findall('<tr>(.*?)</tr>',data);

请建议修复此问题。

只是为了解决这个问题。 尽管与re.M有这些联系, re.M它在这里不起作用,因为它的解释会简单地略读。 你需要re.S ,如果你不想尝试解析html,当然:

>>> doc = """<table border="1">
    <tr>
        <td>row 1, cell 1</td>
        <td>row 1, cell 2</td>
    </tr>
    <tr>
        <td>row 2, cell 1</td>
        <td>row 2, cell 2</td>
    </tr>
</table>"""

>>> re.findall('<tr>(.*?)</tr>', doc, re.S)
['\n        <td>row 1, cell 1</td>\n        <td>row 1, cell 2</td>\n    ', 
 '\n        <td>row 2, cell 1</td>\n        <td>row 2, cell 2</td>\n    ']
>>> re.findall('<tr>(.*?)</tr>', doc, re.M)
[]

不要使用正则表达式,使用HTML解析器,如BeautifulSoup

html = '<html><body>foo<tr>bar</tr>baz<tr>qux</tr></body></html>'

import BeautifulSoup
soup = BeautifulSoup.BeautifulSoup(html)
print soup.findAll("tr")

结果:

[<tr>bar</tr>, <tr>qux</tr>]

如果你只想要内容,没有tr标签:

for tr in soup.findAll("tr"):
    print tr.contents

结果:

bar
qux

使用HTML解析器并不像听起来那么可怕! 并且它将比将在此处发布的任何正则表达式更可靠地工作。

不要使用正则表达式来解析HTML。 使用HTML解析器,例如lxmlBeautifulSoup

pat=re.compile('<tr>(.*?)</tr>',re.DOTALL|re.M)
print pat.findall(data)

或非正则表达方式,

for item in data.split("</tr>"):
    if "<tr>" in item:
       print item[item.find("<tr>")+len("<tr>"):]

正如其他人所说,通过允许使用re.MULTILINE进行多行匹配 ,可以解决您遇到的具体问题

但是, 你正在寻找一个使用正则表达式解析HTML的危险补丁 使用XML / HTML解析器, BeautifulSoup非常适合这个!

doc = """<table border="1">
    <tr>
        <td>row 1, cell 1</td>
        <td>row 1, cell 2</td>
    </tr>
    <tr>
        <td>row 2, cell 1</td>
        <td>row 2, cell 2</td>
    </tr>
</table>"""

from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup(doc)
all_trs = soup.findAll("tr")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM