Python,XPath:查找所有指向图像的链接 [英] Python, XPath: Find all links to images
本文介绍了Python,XPath:查找所有指向图像的链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在Python中使用lxml解析一些HTML,我想提取所有指向图像的链接.我现在的操作方式是:
I'm using lxml in Python to parse some HTML and I want to extract all link to images. The way I do it right now is:
//a[contains(@href,'.jpg') or contains(@href,'.jpeg') or ... (etc)]
此方法有两个问题:
- 您必须列出所有情况下的所有可能的图像扩展名("jpg"和"JPG"),但不够优雅
- 在奇怪的情况下,href可能在中间而不是字符串结尾处包含.jpg
我想使用regexp,但失败了:
I wanted to use regexp, but I failed:
//a[regx:match(@href,'.*\.(?:png|jpg|jpeg)')]
这总是让我获得了所有链接...
This returned me all links all the time ...
有人知道这样做的正确,优雅的方法吗?或者我的regexp方法有什么问题?
Does anyone knows the right, elegant way to do this or what is wrong with my regexp approach ?
推荐答案
而不是:
a[contains(@href,'.jpg')]
使用:
a[substring(@href, string-length(@href)-3)='.jpg']
(对于其他可能的结尾,使用相同的表达模式).
(and the same expression pattern for the other possible endings).
上面的表达式是XPath 1.0,等效于以下XPath 2.0表达式:
a[ends-with(@href, '.jpg')]
这篇关于Python,XPath:查找所有指向图像的链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文