简体   繁体   English

仅刮擦具有相同类simplehtmldom的锚点

[英]Scrape only one Anchor with same class simplehtmldom

I am trying to return only one anchor with the same class name using simplehtmldom, at the moment it returns all the anchors in the page because they all have the same class name. 我试图使用simplehtmldom仅返回一个具有相同类名的锚,此刻它返回页面中的所有锚,因为它们都具有相同的类名。

Here's what I am using: 这是我正在使用的:

foreach($html->find('a.db-link') as $link) {
echo $link->href . '<br>';
echo $link->plaintext . '<br>';
}

From the above I get: 从上面我得到:

http://example.com
link 1
http://example.com/2
link 2
http://example.com/3
link 3

I tried using the find element: 我尝试使用find元素:

echo $link->find('text', 0);

That didn't work. 那没用。

How can I just get the first anchor? 我如何才能获得第一个锚点?

This should work, it's tested: 这应该可以工作,已经过测试:

include_once('simple_html_dom.php');

$html = str_get_html('
<a class="db-link" href="https://www.google.com/1">Google 1</a>
<a class="db-link" href="https://www.google.com/2">Google 2</a>
<a class="db-link" href="https://www.google.com/3">Google 3</a>
<a class="db-link" href="https://www.google.com/4">Google 4</a>
<a class="db-link" href="https://www.google.com/5">Google 5</a>
');


echo $html->find('a.db-link', 0);

Result: 结果:

Google 1 Google 1

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

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