如何在 Python Scrapy 的子 div 中获取带有特殊 src 的 href

How get href with a special src in child div in Python Scrapy

为了获取站点的所有图像,我编写了以下代码:

content = Selector(text = html)
all_images= content.css('img')
i = 0

for image in all_images:
    src =  image.css("::attr('src')").extract_first()

得到图片的src后,现在我想得到每张图片的href

<a href="/rayons/images" onclick="ga('send', 'event', 'computer HP', 'htwe', 'ope_xxl_s22Englos');">
    <img src="/mySrc/" alt="something" class="ze-content">
</a>

当我知道 Src 时,如何获得 href

据我所知,您不能使用 CSS 进行父搜索。在这种情况下,XPath 更合适。你可以这样做:

for image in all_images:
    src =  image.css("::attr('src')").extract_first()
    href = image.xpath('parent::a/@href').extract_first()

或者,使用 XPath 的 abbreviated syntax:

href = image.xpath('../@href').extract_first()