[英]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.