如何用Selenium Python定位指定class下图片的src与alt属性
定位特定带空格class的div下的图片
你的问题核心是要抓取class属性值包含空格的<div>下的<img>元素的src和alt属性,之前的尝试踩了两个小坑:一是XPath只找到了div本身而非里面的图片,二是CSS选择器的写法错把带空格的class当成了多个独立类。下面是两种靠谱的解决方法:
方法1:使用XPath
先定位到目标div,再选择它下面的所有img元素,针对带空格的class属性,有两种写法:
精准匹配class属性值
如果目标div的class属性值就是the class I want(没有其他额外类),直接写:
driver = webdriver.Firefox() driver.get('https://www.somesite.com/somepage') # 定位目标div下的所有img image_elements = driver.find_elements_by_xpath("//div[@class='the class I want']//img") for image in image_elements: img_src = image.get_attribute("src") alt_text = image.get_attribute("alt") # 这里可以添加你的处理逻辑,比如打印或存储 print(f"图片链接:{img_src},Alt文本:{alt_text}")
兼容多类场景
如果目标div可能同时有多个类(比如class="the class I want other-class"),用更严谨的写法避免误匹配:
image_elements = driver.find_elements_by_xpath("//div[contains(concat(' ', @class, ' '), ' the class I want ')]//img")
这种写法会把class属性前后加上空格,确保匹配的是完整的类名片段,不会被类似the class I want-extra的类干扰。
方法2:使用CSS选择器
因为class属性值带空格,不能用.连写(那是用来选择多个独立类的),要改用属性选择器:
精准匹配class属性值
image_elements = driver.find_elements_by_css_selector("div[class='the class I want'] img")
兼容多类场景
如果目标div有多个类,只想匹配包含the class I want的情况,用~=选择器(匹配空格分隔的完整类名):
image_elements = driver.find_elements_by_css_selector("div[class~='the class I want'] img")
如果只是想模糊匹配包含该字符串的class(不推荐,容易误匹配),可以用*=:
image_elements = driver.find_elements_by_css_selector("div[class*='the class I want'] img")
为啥之前的尝试失败了?
- 你的第一个XPath:
//div[contains(@class, 'the class I want')]只找到了目标div元素,没有继续选择它下面的img,所以得在后面加上//img才能定位到图片。 - 你的第二个CSS选择器:
div.the.class.I.want会被解析成“同时拥有the、class、I、want这四个独立类的div”,这和你要找的“class属性值是the class I want”的div完全不是一回事,所以肯定找不到正确元素。
内容的提问来源于stack exchange,提问作者Joe T. Boka
相关产品推荐
相关产品推荐

