用于解析“SRC”的 XPath 来自 IMG 标签?

发布于 2024-07-28 16:45:25 字数 318 浏览 6 评论 0原文

现在,我成功地从 HTML 页面中获取了完整的元素:

//img[@class='photo-large']

例如,它将返回:

<img src="http://example.com/img.jpg" class='photo-large' />

但我只需要 SRC url (http://example.com/img.jpg)。 有什么帮助吗?

Right now I successfully grabbed the full element from an HTML page with this:

//img[@class='photo-large']

for example it would return this:

<img src="http://example.com/img.jpg" class='photo-large' />

But I only need the SRC url (http://example.com/img.jpg). Any help?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

原谅我要高飞 2024-08-04 16:46:08

//img/@src

如果你想要图像的链接,你可以使用这个。

例子:

<img alt="" class="avatar width-full rounded-2" height="230" src="https://avatars3.githubusercontent.com/...;s=460" width="230">

//img/@src

you can just go with this if you want a link of the image.

example:

<img alt="" class="avatar width-full rounded-2" height="230" src="https://avatars3.githubusercontent.com/...;s=460" width="230">
若沐 2024-08-04 16:46:01

使用 Hpricot 可以实现此功能:

doc.at('//img[@class="photo-large"]')['src']

如果您有多个图像,则以下给出一个数组:

doc.search('//img[@class="photo-large"]').map do |e| e['src'] end

但是,Nokogiri快很多倍,而且 “可以用作 Hpricot 的替代品”
这里是 Nokogiri 的版本,其中用于选择属性的 XPath 有效:

doc.at('//img[@class="photo-large"]/@src').to_s

或者对于许多图像:

doc.search('//img[@class="photo-large"]/@src').to_a

Using Hpricot this works:

doc.at('//img[@class="photo-large"]')['src']

In case you have more than one image, the following gives an array:

doc.search('//img[@class="photo-large"]').map do |e| e['src'] end

However, Nokogiri is many times faster and it “can be used as a drop in replacement” for Hpricot.
Here the version for Nokogiri, in which this XPath for selecting attributes works:

doc.at('//img[@class="photo-large"]/@src').to_s

or for many images:

doc.search('//img[@class="photo-large"]/@src').to_a
-残月青衣踏尘吟 2024-08-04 16:45:53

你自己已经很接近回答这个问题了,所以我有点不愿意为你回答。 然而,下面的 XPath 应该提供您想要的内容(当然,前提是源是 XHTML)。

//img[@class='photo-large']/@src

如需更多提示,请查看 W3 学校。 他们有关于此类事情的优秀教程和很好的参考资料。

You are so close to answering this yourself that I am somewhat reluctant to answer it for you. However, the following XPath should provide what you want (provided the source is XHTML, of course).

//img[@class='photo-large']/@src

For further tips, check out W3 Schools. They have excellent tutorials on such things and a great reference too.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文