You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Jsoup解析HTML页面中id为icImg的指定图片?

How to Target the Image with ID "icImg" Instead of Just the First Image

Absolutely! Using an element's unique id is the most reliable way to grab exactly the image you want, since IDs are meant to be one-of-a-kind on a single HTML page. Here's how to do it based on the tool you're using:

Python with BeautifulSoup

If you're parsing HTML in Python with BeautifulSoup, ditch the .first() method and use the find() function with the id parameter directly. This will zero in on your target image instantly:

from bs4 import BeautifulSoup

# Replace with your actual HTML content
html_content = """<img id="icImg" class="img img500" itemprop="image" src="https://i.ebayimg.com/images/g/p4cAAOSwXSNann-Z/s-l500.jpg" style="" onload="picTimer=new Date().getTime();" clk="0" alt="Sigaretta-elettronica-liquid-pronto-per-l-039-uso-svapo-100-ml-GUSTI-A-SCELTA" mskuskip="false">"""

soup = BeautifulSoup(html_content, 'html.parser')
# Target the image by its ID
target_image = soup.find(id='icImg')

# Extract the image source if the element exists
if target_image:
    image_src = target_image['src']
    print(f"Found image URL: {image_src}")

Frontend (jQuery or Vanilla JavaScript)

If you're working directly in the browser (or with a frontend tool):

Using jQuery

Use the ID selector (#icImg) to grab the element immediately:

// Get the target image element
const targetImg = $('#icImg');
// Extract the source attribute
const imgSrc = targetImg.attr('src');
console.log(imgSrc);

Using Vanilla JavaScript

No libraries needed—use the native getElementById() method, which is built specifically for this purpose:

// Get the image by its ID
const targetImg = document.getElementById('icImg');
if (targetImg) {
    // Access the source URL
    const imgSrc = targetImg.src;
    console.log(imgSrc);
}

Key Note

Since HTML standards require IDs to be unique per page, this method will always return exactly the image you're looking for—no more guessing if .first() is picking the right one!

内容的提问来源于stack exchange,提问作者Daniele Asta

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 04:26:50