如何编写 preg_match_all 仅用于抓取一个特定元素?
在该网站允许我访问他的 API 之前,我只需要显示该网站的 2 件事:
这两个内容包含在 div 中:
<div style="float: right; margin: 10px;">
here what i want to display on my website
</div>
问题是我在stackoverflow上找到了一个例子,但我以前从未写过preg_match。 如何处理我想要抓取的数据?谢谢
<?php $html = file_get_contents($st_player_cv->getUrlEsl());
preg_match_all(
'What do i need to write here ?',
$html,
$posts, // will contain the data
PREG_SET_ORDER // formats data into an array of posts
);
foreach ($posts as $post) {
$premium = $post[1];
$level = $post[2];
// do something with data
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
执行此操作的 DOM 方法是
但是 页面中存在大量 JavaScript,它们会在页面加载后大量修改 DOM。由于任何基于 PHP 脚本的获取都不会执行任何 JavaScript,因此我们在 XPath 中搜索的样式尚不存在,我们不会得到任何结果(Hannes 建议的正则表达式出于同样的原因不起作用)。徽章上的等级数字也还不存在。
正如 Wrikken 在评论中指出的那样,似乎还有某种机制可以阻止某些请求。我曾经收到过该消息,但我不确定是什么触发了它,因为我也可以多次获取页面。
长话短说:您无法通过此页面实现您想要做的事情。
The DOM way to do it would be
but there is a whole slew of JavaScript in the page that modifies the DOM heavily after the page was loaded. Since any PHP script based fetching will not execute any JavaScript, the style we search for in the XPath does not exist yet and we won't get any results (the Regex suggesed by Hannes doesn't work for the same reason). Neither do the level numbers on the badge exist yet.
As Wrikken pointed out in the comments, there also seems to be some mechanism to block certain requests. I had the message once, but I am not sure what triggers it, because I could also fetch page on several occasions.
To cut a long story short: you cannot achieve what you are trying to do with this page.
如果你想要更通用的
$myhtml
包含你必须分析的代码 html。$result
是包含正则表达式应用后的 regexp 和()
内容的数组。$result[1]
将为您提供和
之间的内容。
这样,即使 不同(类名更改或属性不同),它仍然可以工作。
If you want something more generic
$myhtml
contains the code html you have to analyze.$result
is the array that contains the regexp and()
content after the regular expression was applied.$result[1]
will give you what is between the<div ... >
and</div>
.This way, even if the
<div
differs (class name change or different attributes), it'll still work.这个正则表达式
'#
#'
应该可以解决问题(是的),但我建议你使用 DOM & X 路径。编辑:
这是一个 Xpath / DOM 示例:
this regex
'#<div style="float: right; margin: 10px;">(.*)</div>#'
should do the trick (yeah) but i would advice you to use DOM & XPath.edit:
Here is an Xpath / DOM Example: