[英]Extract text from HTML with Javascript
我想使用純Javascript從HTML提取文本(這是針對Chrome擴展程序)。
具體來說,我希望能夠在頁面上找到文本並在其后提取文本。
更具體地說,在類似
https://picasaweb.google.com/kevin.smilak/BestOfAmericaSGrandCircle#4974033581081755666
我想查找“緯度”文本並提取其后的值。 HTML並不是一種非常結構化的形式。
有什么優雅的解決方案?
我認為沒有優雅的解決方案,因為正如您所說的,HTML不是結構化的,並且“緯度”和“經度”一詞取決於頁面的本地化。 我能想到的最好的是依靠基本觀點,這可能不會改變...
var data = document.getElementById("lhid_tray").innerHTML;
var lat = data.match(/((\d)*\.(\d)*)°(\s*)(N|S)/)[1];
var lon = data.match(/((\d)*\.(\d)*)°(\s*)(E|W)/)[1];
你可以做
var str = document.getElementsByClassName("gphoto-exifbox-exif-field")[4].innerHTML;
var latPos = str.indexOf('Latitude')
lat = str.substring(str.indexOf('<em>',latPos)+4,str.indexOf('</em>',latPos))
您感興趣的文本位於類gphoto-exifbox-exif-field
的div
。 由於這是針對Chrome擴展程序的,因此我們擁有document.querySelectorAll
,可以輕松選擇該元素:
var div = document.querySelectorAll('div.gphoto-exifbox-exif-field')[4],
text = div.innerText;
/* text looks like:
"Filename: img_3474.jpg
Camera: Canon
Model: Canon EOS DIGITAL REBEL
ISO: 800
Exposure: 1/60 sec
Aperture: 5.0
Focal Length: 18mm
Flash Used: No
Latitude: 36.872068° N
Longitude: 111.387291° W"
*/
現在很容易獲得您想要的東西:
var lng = text.split('Longitude:')[1].trim(); // "111.387291° W"
我使用trim()
而不是split('Longitude: ')
因為那實際上不是innerText
的空格字符(URL編碼,它是%C2%A0
。。。沒有時間弄清楚映射到的內容,對不起)。
我將查詢DOM並將圖像信息收集到一個對象中,以便您可以引用所需的任何屬性。
例如
function getImageData() {
var props = {};
Array.prototype.forEach.apply(
document.querySelectorAll('.gphoto-exifbox-exif-field > em'),
[function (prop) {
props[prop.previousSibling.nodeValue.replace(/[\s:]+/g, '')] = prop.textContent;
}]
);
return props;
}
var data = getImageData();
console.log(data.Latitude); // 36.872068° N
好吧,如果其他站點需要更一般的答案,那么您可以嘗試以下方法:
var text = document.body.innerHTML;
text = text.replace(/(<([^>]+)>)/ig,""); //strip out all HTML tags
var latArray = text.match(/Latitude:?\s*[^0-9]*[0-9]*\.?[0-9]*\s*°\s*[NS]/gim);
//search for and return an array of all found results for:
//"latitude", one or 0 ":", white space, A number, white space, 1 or 0 "°", white space, N or S
//(ignores case)(ignores multi-line)(global)
對於該示例,將返回一個包含1個元素的數組,其中包含“緯度:36.872068°N”(應該易於解析)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.