如何通过lxml XPath从HTML中提取img src?

时间:2018-03-02 02:01:33

标签: python html xpath web-scraping lxml

我正在尝试使用python / lxml和xpath()命令提取图像URl,但是在隔离网址本身时遇到了问题。

以下是我想要的img src周围的HTML:

<div data-index="0" data-za-action="Photo Lightbox - Open" data-za-
category="Homes" class="img-wrapper za-track-event zsg-lightbox-show" 
data-target-id="hdp-photo-lightbox" data-za-label="position: 0, total: 
18, id: 10660534745" id="yui_3_18_1_2_1519884476676_1986"><img 
src="https://photos.zillowstatic.com/p_h/IS2fordnekys6d1000000000.jpg" 
onload="if (typeof ClientProfiler !== 'undefined') { 
ClientProfiler.profile('HDPFirstPhotoLoaded') }" id="X1-
IAgz3dcnekys6d1000000000_ptw8e" class="hip-photo"></div>

具体来说,我想隔离https://photos.zillowstatic.com/p_h/IS2fordnekys6d1000000000.jpg网址。

我尝试了一些没有成功的方法,包括以下内容的变体:

xpath(".//img[@class='hip-photo']/@src")
xpath(".//img[@class='hip-photo']//text()")

2 个答案:

答案 0 :(得分:1)

LPTSTR messageBuffer;相对于当前节点进行搜索,这在您的问题中未指定。如果您使用.//,则会搜索整个文档。另请参阅What is the difference between .// and //* in XPath?

如果您希望搜索整个文档XPath,

//

将选择所有//img[@class="hip-photo"]/@src 元素的src个属性img属性值为class

答案 1 :(得分:0)

我会尝试Beautifulsoup(bs4)库。你的img标签有一个id,所以你可以在bs4中调用find函数。

source_code.find('img', id=its_id)

然后从标签中获取scr。

Similar question regarding your problem

bs4 Youtube tutorial if you're new to it

如果你之前从未使用过,那么Beautifulsoup非常容易学习,所以我建议你去研究它。

希望这有帮助!

相关问题