可能重复:
RegEx match open tags except XHTML self-contained tags
从标签中仅提取文本的最佳正则表达式是什么?如果我有这种html标记
<tr class="classo">
<td>text1</td>
<td class="dot">text2 </td>
<td>text3</td>
<td class="dot"> text4</td>
<td class="dot">text4</td>
</tr>
td标签的数量不固定,其中一些也有class属性,但我只对从td标签内部获取文本感兴趣
答案 0 :(得分:2)
不要花时间使用正则表达式,而是使用专为此任务设计的内容。我喜欢BeautifulSoup:
>>> s = """
... <tr class="classo">
... <td>text1</td>
... <td class="dot">text2 </td>
... <td>text3</td>
... <td class="dot"> text4</td>
... <td class="dot">text4</td>
... </tr>
... """
>>>
>>> from bs4 import BeautifulSoup
>>> soup = BeautifulSoup(s)
>>> soup.find_all("td")
[<td>text1</td>, <td class="dot">text2 </td>, <td>text3</td>, <td class="dot"> text4</td>, <td class="dot">text4</td>]
>>> [tag.text for tag in soup.find_all("td")]
[u'text1', u'text2 ', u'text3', u' text4', u'text4']
答案 1 :(得分:1)
正则表达式<td.*?>(.*?)<\/td>
将正确执行。
但我可以建议您使用HTMLParser Module或BeautifulSoup
让我花时间用HTMLParser写下另一个例子:
from HTMLParser import HTMLParser
class TDExtractor(HTMLParser):
def handle_starttag(self, tag, attrs):
if tag == 'td':
self.recording = True
def handle_endtag(self, tag):
if tag == 'td':
self.recording = False
def handle_data(self, data):
if self.recording:
self.data.append(data)
def reset(self):
HTMLParser.reset(self)
self.data = []
self.recording = False
行动中:
> tdextractor = TDExtractor()
> tdextractor.feed(some_htmldata)
> print(tdextractor.data) # will print a list with all the td data.
答案 2 :(得分:1)
正则表达式不是为解析HTML而设计的。 HTML不是常规语言,使用正则表达式无法轻松解析。
很多人都喜欢BeautifulSoup
,但它非常slow(another source),不如lxml
,甚至可以使用BeautifulSoup
作为需要的解析器。
以下是使用lxml
的解决方案。
>>> import lxml.html
>>> html = lxml.html.fromstring("""
... <tr class="classo">
... <td>text1</td>
... <td class="dot">text2 </td>
... <td>text3</td>
... <td class="dot"> text4</td>
... <td class="dot">text4</td>
... </tr>""")
>>> print [e.text for e in html.xpath("td")]
['text1', 'text2 ', 'text3', ' text4', 'text4']