【问题标题】:How get href with a special src in child div in Python Scrapy如何在 Python Scrapy 的子 div 中使用特殊的 src 获取 href
【发布时间】:2017-11-07 12:25:39
【问题描述】:

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

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

【问题讨论】:

    标签: python xpath css-selectors scrapy selector


    【解决方案1】:

    AFAIK,您不能使用 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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-16
      • 2020-02-27
      • 2021-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-24
      • 2015-06-11
      相关资源
      最近更新 更多