繁体   English   中英

使用正则表达式从html标记中提取文本

[英]extract text from html tags using regex

我的HTML文本如下所示。我只想在python中使用REGEX从HTML文本中提取纯文本(不使用HTML注释)

<p style="text-align: justify;"><span style="font-size: small; font-family: lato, arial, h elvetica, sans-serif;">
Irrespective of the kind of small business you own, using traditional sales and marketing tactics can prove to be expensive.
</span></p>

如何找到确切的正则表达式以获取纯文本?

您可以使用Java使用简单的选择器方法来执行此操作,然后检索.innerHTML属性。

//select the class for which you want to pull the HTML from
let div = document.getElementsByClassName('text-div');
//select the first element of NodeList returned from selector method and get the inner HTML 
let text = div[0].innerHTML; 

这将选择要检索其HTML的元素,然后将提取内部HTML文本,假设您只想要HTML标记之间的内容,而不是标记本身。

正则表达式不是必需的。 您必须使用JS或某些后端来实现Regex,只要您可以在项目中插入JS脚本,就可以获取内部HTML。

如果您要抓取数据,则无论使用哪种语言,您的库都极有可能使用选择器方法和方法来轻松检索HTML文本,而无需使用正则表达式。

您最好在这里使用解析器:

import html, xml.etree.ElementTree as ET

# decode
string = """<p style="text-align: justify;"><span style="font-size: small; font-family: lato, arial, h elvetica, sans-serif;">
Irrespective of the kind of small business you own, using traditional sales and marketing tactics can prove to be expensive.
</span></p>"""

# construct the dom
root = ET.fromstring(html.unescape(string))

# search it
for p in root.findall("*"):
    print(p.text)

这产生

Irrespective of the kind of small business you own, using traditional sales and marketing tactics can prove to be expensive.

显然,您可能想要更改xpath ,从而查看可能性


附录:

可以在此处使用正则表达式,但是这种方法确实容易出错并且不建议使用

import re

string = """<p style="text-align: justify;"><span style="font-size: small; font-family: lato, arial, h elvetica, sans-serif;">
Irrespective of the kind of small business you own, using traditional sales and marketing tactics can prove to be expensive.
</span></p>"""

rx = re.compile(r'(\b[A-Z][\w\s,]+\.)')

print(rx.findall(string))
# ['Irrespective of the kind of small business you own, using traditional sales and marketing tactics can prove to be expensive.']

这个想法是寻找一个大写字母并匹配单词字符,空格和逗号,直到一个点。 参见regex101.com上的演示

暂无
暂无

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

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