[英]how do I select xpath image without a class name using selenium in python?
我如何 select 圖像 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)
時它返回一個[]
(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
返回列表,使用 index 獲取第一個元素。
如果你想使用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')
實際上 xpath 已正確復制,您在獲取代碼中以錯誤的方式使用它。
如果您想要特定圖像,請使用
image = driver.find_element_by_xpath('//*[@id="sortable-results"]/ul/li[1]/a/img')
或者,如果您想要相同 xpath 類型的所有圖像的列表,請使用:
images = driver.find_elements_by_xpath('//*[@id="sortable-results"]/ul/li/a/img')
(即刪除特定數量的 'li' div 或您想要概括並使用find_elements的任何其他 div;您需要使用find_element來獲取特定的單個元素)
要獲取屬性 'src',請使用get_attribute方法:
對於案例 1:
website = image.get_attribute('src')
對於案例 2:
website = images[0].get_attribute('src')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.