Skip to main content
 首页 » 编程设计

python之如何在 python 中使用 selenium 选择没有类名的 xpath 图像

2025年05月04日19www_RR

如何选择没有类名的图像 xpath。 HTML代码是这样的

<img alt="" class src="https://images.craigslist.org/00J0J_i9BI6mN6rKP_300x300.jpg">

如果我右键单击并复制 xpath,它会给我这个 //*[@id="sortable-results"]/ul/li[1]/a/img但是当我在我的代码中使用它时出现了一些错误

在我的代码中我这样使用

 src = driver.find_elements_by_xpath('/li[@class="result-row"]/a[@class="result-image gallery"]/img[@class=""]/@src') 

但它返回一个 []当我 print(src)

完整的 div

<li class="result-row" data-pid="7017735595"> 
 
        <a href="https://vancouver.craigslist.org/van/ele/d/vancouver-sealed-brand-new-in-box/7017735595.html" class="result-image gallery" data-ids="1:00J0J_i9BI6mN6rKP"><img alt="" class="" src="https://images.craigslist.org/00J0J_i9BI6mN6rKP_300x300.jpg"> 
                <span class="result-price">$35</span> 
        </a> 
 
    <p class="result-info"> 
        <span class="icon icon-star" role="button" title="save this post in your favorites list"> 
            <span class="screen-reader-text">favorite this post</span> 
        </span> 
 
            <time class="result-date" datetime="2019-11-11 00:52" title="Mon 11 Nov 12:52:25 AM">Nov 11</time> 
 
 
        <a href="https://vancouver.craigslist.org/van/ele/d/vancouver-sealed-brand-new-in-box/7017735595.html" data-id="7017735595" class="result-title hdrlnk">Sealed - Brand New in Box - Google Home Mini</a> 
 
 
        <span class="result-meta"> 
                <span class="result-price">$35</span> 
 
 
                <span class="result-hood"> (Vancouver)</span> 
 
                <span class="result-tags"> 
                    <span class="pictag">pic</span> 
                </span> 
 
                <span class="banish icon icon-trash" role="button"> 
                    <span class="screen-reader-text">hide this posting</span> 
                </span> 
 
            <span class="unbanish icon icon-trash red" role="button" aria-hidden="true"></span> 
            <a href="#" class="restore-link"> 
                <span class="restore-narrow-text">restore</span> 
                <span class="restore-wide-text">restore this posting</span> 
            </a> 
 
        </span> 
    </p> 
</li> 

请您参考如下方法:

xpath 很接近。您需要在路径的开头使用 // 并删除 /@src

//li[@class="result-row"]/a[@class="result-image gallery"]/img[@class=""] 

如果你想确保元素有 src 属性,就这样

//li[@class="result-row"]/a[@class="result-image gallery"]/img[@class=""][@src] 

要获取 src 属性,请使用 get_attribute('src)

src = driver.find_elements_by_xpath('//li[@class="result-row"]/a[@class="result-image gallery"]/img[@class=""]')[0].get_attribute('src') 

注意find_elements返回列表,使用索引获取第一个元素。

如果你想使用class="result-info"定位你可以做的元素

elements = driver.find_elements_by_xpath('//p[@class="result-info"]/../a[@class="result-image gallery"]/img[@class=""]') 
for element in elements: 
    src = element.get_attribute('src')