使用php将URL匹配到模式
我必须为我的项目使用爬虫 我使用简单的dom类从一个页面获取所有链接使用php将URL匹配到模式,php,Php,我必须为我的项目使用爬虫 我使用简单的dom类从一个页面获取所有链接 现在我只想过滤那些形式为“/questions/3904482/的链接,你说url是question*s*,但你的模式显示没有 另外,看起来您应该使用if而不是echo include_once('simple_html_dom.php'); $html = new simple_html_dom(); $html->load_file('http://stackoverflow.com/questions?sort=n
现在我只想过滤那些形式为
“/questions/3904482/的链接,你说url是question*s*,但你的模式显示没有
另外,看起来您应该使用if
而不是echo
include_once('simple_html_dom.php');
$html = new simple_html_dom();
$html->load_file('http://stackoverflow.com/questions?sort=newest');
$pat='#^/questions/([0-9]+)/#';
foreach($html->find('a') as $link)
{
if ( preg_match($pat, $link->href) )
{
echo $link->href."<br>";
}
}
include_once('simple_html_dom.php');
$html=新的简单html\U dom();
$html->load_文件($html)http://stackoverflow.com/questions?sort=newest');
$pat='#^/问题/([0-9]+)/#';
foreach($html->find('a')as$link)
{
如果(preg_匹配($pat,$link->href))
{
echo$link->href.“
”;
}
}
您可以利用DOM和XPath:
<?php
$dom = new DOMDocument;
@$dom->loadHTMLFile('http://stackoverflow.com/questions?sort=newest');
$xpath = new DOMXPath($dom);
$questions = $xpath->query("//a[contains(@href, '/questions/') and not(contains(@href, '/tagged/')) and not(contains(@href, '/ask'))]");
foreach ($questions as $question) {
print "{$question->getAttribute('href')} => {$question->nodeValue}";
}
您说url是有问题的,但您的模式显示没有问题s@user2969918我的答案对你有用吗?:)看起来不错,但是如果使用了@
操作符,那么可能应该检查$dom
的值:)
。是的,我在这里使用它只是为了抑制加载htmlfile()
输出警告(对于格式不正确的文件)。另一种方法是在前面调用libxml\u use\u internal\u errors(true);
。)
<?php
$dom = new DOMDocument;
@$dom->loadHTMLFile('http://stackoverflow.com/questions?sort=newest');
$xpath = new DOMXPath($dom);
$questions = $xpath->query("//a[contains(@href, '/questions/') and not(contains(@href, '/tagged/')) and not(contains(@href, '/ask'))]");
foreach ($questions as $question) {
print "{$question->getAttribute('href')} => {$question->nodeValue}";
}