以下地址有一个货币兑换网站:
https://www.tgju.org/currency
我如何购买美元和...等价格?
我有一个示例代码,它使用“file_get_contents”仅查找一个特定的类 我的代码:
$content = file_get_contents("https://www.tgju.org/currency");
$dom = new DOMDocument();
$dom->loadHTML($content);
$finder = new DomXPath($dom);
$classname = "nf";
$nodes = $finder->query("//*[contains(concat(' ', normalize-space(@class), ' '), ' $classname ')]");
$data1 = $nodes{0}->nodeValue;
感谢您帮助我完成代码
查看 HTML,我发现美元行的
data-market-row
属性设置为 price_dollar_rl
。然后是你想阅读的所有信息
然后存储在一些 <td>
单元格中。
因此,您可以更改 XPath 查询以获取所有这些单元格,然后采取 您想要的价值:
<?php
$content = file_get_contents("https://www.tgju.org/currency");
$dom = new DOMDocument();
$dom->loadHTML($content) or die('Could not parse the HTML correctly!');
$finder = new DomXPath($dom);
$cells = $finder->query('//tr[@data-market-row="price_dollar_rl"]/td');
print "Found $cells->length <td> cells for US Dollar\n";
foreach ($cells as $index => $cell) {
print "Cell n°$index: $cell->nodeValue \n";
}
// To get just the first cell:
// A) Just read item 0 from above's query.
print 'Accessing item 0: ' . $cells->item(0)->nodeValue . "\n";
// B) Change your XPath query to get the first <td> with the "nf" class.
$cells = $finder->query(
'//tr[@data-market-row="price_dollar_rl"]//td[contains(concat(" ",normalize-space(@class)," ")," nf ")][1]'
);
print 'Accessing first td with class "nf" inside dollar row: ' . $cells->item(0)->nodeValue . "\n";
输出:
Found 6 <td> cells for US Dollar
Cell n°0: 490,160
Cell n°1: (0.3%) 1,460
Cell n°2: 489,480
Cell n°3: 491,010
Cell n°4: Û±Û¶:Û±Û´:Û´Û¶
Cell n°5:
Accessing item 0: 490,160
Accessing first td with class "nf" inside dollar row: 490,160