在[Python]中查找所有TR(来自html <table>)

MAG*_*Gx2 1 python regex html-parsing

我希望得到我所有的内容.我写了这段代码:

matchObj = re.search(r'<tr>(.*?)</tr>', txt, re.M|re.I|re.S)
Run Code Online (Sandbox Code Playgroud)

但我只得到了第一组.

我怎样才能获得所有团体?

提前致谢 :)

Inb*_*ose 8

findall

matchObj = re.findall(r'<tr>(.*?)</tr>', txt, re.M|re.I|re.S)
Run Code Online (Sandbox Code Playgroud)

search 只找到给定字符串中的第一个.

您可以阅读有关可以在正则表达式中使用的不同方法的更多信息.

但是,看起来你正在解析HTML.为什么不使用HTMl解析器


Mar*_*ers 5

要获得多场比赛,请使用re.findall().

然而,使用正则表达式来解析 HTML 很快就会变得丑陋且复杂。请改用适当的 HTML 解析器。

Python 有以下几种可供选择:

元素树示例:

from xml.etree import ElementTree

tree = ElementTree.parse('filename.html')
for elem in tree.findall('tr'):
    print ElementTree.tostring(elem)
Run Code Online (Sandbox Code Playgroud)

美丽汤示例:

from bs4 import BeautifulSoup

soup = BeautifulSoup(open('filename.html'))
for row in soup.select('table tr'):
    print row
Run Code Online (Sandbox Code Playgroud)