【问题标题】:Scrape complete HTML tag wise明智地抓取完整的 HTML 标记
【发布时间】:2017-07-24 13:20:27
【问题描述】:

假设我有一个 HTML 页面

<p> Some text here </p>
<p> Some other text here </p>
<h1> Title 1 </h1>
<p> Another text here </p>
<p> Some random text here </p>
<h1> Title 2 </h1>
<p> Some text here </p>
<p> Some other text here </p>
<h1>..<h1>

是否可以逐个标签抓取内容的标签

if (<h1>)
then do something

if (<p>)
then do something else

对于每个标签

【问题讨论】:

  • 那么你想要做的是你想要遍历所有的 html 元素并为每个元素做一些事情?
  • 签出 Jsoup 库 (jsoup.org/apidocs)。它有很多方法可以帮助您完成需要的工作
  • @RandomDeveloper - 是的,我想遍历每个标签,然后应用必要的条件
  • 我尝试使用 simplehtmldom.sourceforge.net ,很好地将

    标签作为 $article->find('h1')->plaintext

  • 可能类似于在 php 中排列的 html 标签?

标签: php html web-scraping custom-selectors


【解决方案1】:

php getElementsByTagName() 按标签名称选择元素。如果你把*放在函数参数中,它会返回所有元素。

$dom = new DOMDocument();
$dom->loadHTML($html);
foreach ($dom->getElementsByTagName('*') as $element){
    if ($element->tagName == "h1")
        // do something
    if ($element->tagName == "p")
        // do something
}

检查结果在demo

【讨论】:

    猜你喜欢
    • 2019-06-17
    • 1970-01-01
    • 2014-04-02
    • 1970-01-01
    • 2014-06-21
    • 1970-01-01
    • 1970-01-01
    • 2021-06-29
    • 2018-01-19
    相关资源
    最近更新 更多