1

我目前正在构建一些东西来查看 ebay 拍卖,但我很难阻止它包含“更多相关项目”之后的项目,这显然是我不想要的。

目前,所有链接都是标准的 a href,布局为

<a href="http://www.ebay.co.uk/blahblah" class="vip" title="x" itemprop="name">

class="vip" 在每个项目链接中,所以这似乎是一个好用的东西,但是它也在相关项目的链接中,所以我不需要比与部分相关的更多项目更进一步。

它需要是正则表达式,因为我是用 ubot 制作的(比用真正的语言编码要快得多) - 很抱歉这个菜鸟问题,正则表达式无论如何都不是我的强项。

谢谢!:)

4

2 回答 2

1

描述

这个正则表达式将:

  • 匹配所有具有class属性的锚标记vip
  • 捕获href这些锚标记的属性值
  • 将避免有问题的边缘情况
  • 允许classhref以任意顺序出现在锚标签中
  • more to explore部分后不捕获

<a\b(?=\s)(?=(?:[^>=]|='[^']*'|="[^"]*"|=[^'"][^\s>]*)*?\shref=('[^']*'|"[^"]*"|[^'"][^\s>]*))(?=(?:[^>=]|='[^']*'|="[^"]*"|=[^'"][^\s>]*)*?\sclass=['"]?vip['"]?)(?:[^>=]|='[^']*'|="[^"]*"|=[^'"\s]*)*"\s?>.*?</a>(?=.*?More\sto\sexplore)

在此处输入图像描述

PHP 代码示例:

示例文本

注意第二行有一些可能有问题的文本

<a href="http://www.ebay.co.uk/blahblah-11" class="vip" title="x" itemprop="name">text here</a>
<a onmouseover=' var class="vip"  ; funClassSwap(class); ' href="http://www.ebay.co.uk/blahblah-22"><form><input type="image" src="submit.gif"></form></a>
<a class="vip" href="http://www.ebay.co.uk/blahblah-33" title="x" itemprop="name">more text</a>
<div class="seoi-c">
    <h2 class="seoi-h">More to explore</h2>
    <div class="fl">
        <ul class="tso-u">
                <li><a href="http://www.ebay.com/sch/Lathes-/97230/i.html?_dcat=97230&amp;Type=CNC&amp;_trksid=p2045573.m2389" title="Lathes in Metalworking Equipment CNC">Lathes in Metalworking Equipment CNC</a></li>
        </ul>
    </div>
    <div class="fl">
        <ul class="tso-u">
        </ul>
    </div>
</div>
<a class="vip" href="http://www.ebay.co.uk/blahblah-44" title="x" itemprop="name">more text</a>

代码

<?php
$sourcestring="your source string";
preg_match_all('/<a\b(?=\s) # capture the open tag
(?=(?:[^>=]|=\'[^\']*\'|="[^"]*"|=[^\'"][^\s>]*)*?\shref=(\'[^\']*\'|"[^"]*"|[^\'"][^\s>]*)) # get the href attribute
(?=(?:[^>=]|=\'[^\']*\'|="[^"]*"|=[^\'"][^\s>]*)*?\sclass=[\'"]?vip[\'"]?) # validate the class attribute
(?:[^>=]|=\'[^\']*\'|="[^"]*"|=[^\'"\s]*)*"\s?> # get the entire tag
.*?<\/a>   # capture the entire anchor tag
(?=.*?More\sto\sexplore)  # validate this match is before the 'more to explore' section
/imsx',$sourcestring,$matches);
echo "<pre>".print_r($matches,true);
?>

火柴

[0][0] = <a href="http://www.ebay.co.uk/blahblah-11" class="vip" title="x" itemprop="name">text here</a>
[0][2] = "http://www.ebay.co.uk/blahblah-11"
[1][0] = <a class="vip" href="http://www.ebay.co.uk/blahblah-33" title="x" itemprop="name">more text</a>
[1][3] = "http://www.ebay.co.uk/blahblah-33"
于 2013-07-06T01:58:12.370 回答
0

我发现使用“运行 JavaScript”功能对于从页面中删除您不想抓取的不需要的内容非常有用。找到“更多相关项目”部分的 ID 或类别,然后执行以下操作:

x = document.getElementById("more items id"); x.remove()

这会将其从页面中删除。然后,您可以告诉机器人开始抓取。

于 2015-05-24T05:21:52.300 回答