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

问题描述 投票:0回答:2

我正在尝试使用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()")
python html xpath web-scraping lxml
2个回答
1
投票

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

如果你想搜索整个文件XPath,

//img[@class="hip-photo"]/@src

将使用src属性值img选择所有class元素的所有"hip-photo"属性。


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非常容易学习,所以我建议你去研究它。

希望这可以帮助!

© www.soinside.com 2019 - 2024. All rights reserved.