【问题标题】:How to search html file for simple string?如何在 html 文件中搜索简单的字符串?
【发布时间】:2011-08-22 21:16:34
【问题描述】:

Consider this link from Amazon.

如果您注意到,每个卖家都有这个块(至少相似):

<a href="http://www.amazon.com/shops/AN8LN2YPKS7DF/ref=olp_merch_name_2">
<img src="http://ecx.images-amazon.com/images/I/41UQmT7-XyL.jpg" width="120" alt="DataVision Computer Video" height="30" border="0" />
</a> //and other junk

我想在这个页面搜索http://ecx.images-amazon.com/images/I/41UQmT7-XyL.jpg,这是卖家的图片(我已经有了链接)。我只想知道搜索是否产生了结果。我什至不需要知道更多。这可能吗?如何使用 PHP 来实现?

【问题讨论】:

  • 使用 HTML 解析器。见Best methods to parse HTML with PHP
  • 您要搜索本地文件还是在线文件?
  • @David:我想在它在线时搜索它。
  • @Pekka:我不想解析 html。我想在服务器上下载 html 并查看是否存在简单字符串。解析似乎有点过头了。
  • @Shorty 啊,很公平。

标签: php web-scraping


【解决方案1】:

你可以使用strpos():

$url = "http://www.example.com/";
$html = file_get_contents($url);
if (strpos($html, "http://ecx.images-amazon.com/images/I/41UQmT7-XyL.jpg") !== false) {
  // found
} else {
  // not found
}

【讨论】:

  • 如何下载 html 放入变量中?
  • $html = file_get_contents($url)
  • 奇怪,得到这个错误:Parse error: syntax error, unexpected T_IF in...
  • 您可能在错误消息中的行号之前错过了行外的分号或右括号...
  • 是的,我做到了。现在我收到Parse error: syntax error, unexpected ')' 。不过,看起来我并没有缺少右括号。
【解决方案2】:

如果您只想知道某个特定字符串是否存在,请使用strpos()

if (strpos($html_goes_here, 'http://ecx.blahblah.jpg') !== FALSE)) {
   ... image is present ...
}

请注意严格比较运算符的使用,根据链接文档页面上的警告。

【讨论】:

    【解决方案3】:

    我在评论中混合了参数,您想知道如何加载 URL 的 HTML:

    $url = "http://rads.stackoverflow.com/amzn/click/B00519RW1U";
    $html = file_get_contents($url);
    $found = false !== strpos($html, 'src="http://ecx.images-amazon.com/images/I/41UQmT7-XyL.jpg"');
    

    【讨论】:

    • 缺少分号,为什么将 url 作为系统命令执行? ;-)
    • 谢谢。但是,您确实搞砸了第一行。应该用引号 "" 而不是反引号,并且缺少分号。
    猜你喜欢
    • 1970-01-01
    • 2012-01-12
    • 2018-03-30
    • 2016-06-04
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-07
    相关资源
    最近更新 更多