javascript 如何使用简单的 html dom 获取 div 内部文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5284118/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 16:38:21  来源:igfitidea点击:

how to use simple html dom get a div inner text

javascripthtmldom

提问by cj333

<div style="float: left; margin-top: 10px; font-family: Verdana; font-size: 13px; color: #404040;">innertext</div>

Jow can I access innertext of divs not having classor idbut spanusing simple html dom php parser? Thanks.

宙能否访问的innerText的没有申报单classidspan使用简单的HTML DOM PHP解释?谢谢。

回答by Ben Blank

If the styles are consistent, then you can loop over all divs in the document and filter them by style.

如果样式一致,那么您可以遍历文档中的所有 div 并按样式过滤它们。

var divs = document.getElementsById("div");

for (var i = 0; i < divs.length; i++) {
    var div = divs[i];

    // skip the current div if its styles are wrong
    if (div.style.cssFloat !== "left"
     || div.style.marginTop !== "10px"
     || div.style.fontFamily !== "Verdana"
     || div.style.fontSize !== "13px"
     || div.style.color !== "#404040") continue;

    var text = div.innerText || div.textContent;

    // do something with text
}

回答by gurjeet kj

You may use the content of styletag if no idor classis given there like:

style如果没有idclass在那里给出,您可以使用标签的内容,例如:

include('simple_html_dom.php');
$html = file_get_html('http://www.mysite.com/');
foreach($html->find('div[style="float: left; margin-top: 10px; font-family: Verdana; font-size: 13px; color: #404040;"]') as $e)
echo $e->innertext;

回答by rdamborsky

You could probably try to match some of their parents (which have classor idset), then traverse the DOM to the child you want.

您可能会尝试匹配他们的一些父级(已设置class或已id设置),然后将 DOM 遍历到您想要的子级。

回答by cj333

Thanks to all. I depends on simple_html_domtoo much, Ben Blank give me a good way. And I also tried php regular-expression to match the div by myself.

谢谢大家。我simple_html_dom太依赖了,Ben Blank 给我一个好方法。而且我还尝试了 php 正则表达式来自己匹配 div。

preg_match_all('/<div.*(style="float: left; margin-top: 10px; font-family: Verdana; font-size: 13px; color: #404040;").*>([\d\D]*)<\/div>/iU',$html,$match);
print_r($match);