gpt4 book ai didi

php - 用通配符和 php 抓取

转载 作者:可可西里 更新时间:2023-11-01 13:27:05 24 4
gpt4 key购买 nike

我很难想象和构想去抓取此页面:http://www.morewords.com/ends-with/aw对于单词本身。给定一个 URL,我想获取内容,然后生成一个包含所有列出的单词的 php 数组,在源代码中看起来像

<a href="/word/word1/">word1</a><br />
<a href="/word/word2/">word2</a><br />
<a href="/word/word3/">word3</a><br />
<a href="/word/word4/">word4</a><br />

我一直在考虑执行此操作的几种方法,如果您能帮助我确定最有效的方法,我将不胜感激。另外,我将不胜感激有关如何实现这一目标的任何建议或示例。我知道这不是非常复杂,但我需要你们高级黑客的帮助。

  • 使用某种 jquery $.each() 循环并以某种方式将它们放入 JS 数组中,然后转录(可能很费力)
  • 使用某种 curl(对 curl 没有太多经验)
  • 使用一些复杂的查找并用正则表达式替换。

最佳答案

您将其标记为 PHP,因此这是一个 PHP 解决方案:)

$dom = new DOMDocument;

$dom->loadHTMLFile('http://www.morewords.com/ends-with/aw');

$anchors = $dom->getElementsByTagName('a');

$words = array();

foreach($anchors as $anchor) {
if ($anchor->hasAttribute('href') AND preg_match('~/word/\w+/~', $anchor->getAttribute('href'))) {
$words[] = $anchor->nodeValue;
}
}

CodePad .

如果allow_url_fopenphp.ini 中被禁用,您可以使用 cURL 获取 HTML。

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'http://www.morewords.com/ends-with/aw');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$html = curl_exec($curl);
curl_close($curl);

关于php - 用通配符和 php 抓取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5905215/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com