代码之家  ›  专栏  ›  技术社区  ›  Amir Asyraf

无法使用Scrapy从父节点和子节点/标记获取文本

  •  3
  • Amir Asyraf  · 技术社区  · 7 年前

    1. scrapy css selector: get text of all inner tags
    2. How to get the text from child nodes if it is parents to other node in Scrapy using XPath
    3. scrapy get the entire text including children

    <span class="location">
        Mandarin Oriental Hotel
        <a class="" href="/search-results/Jalan+Pinang%252C+Kuala+Lumpur+City+Centre%252C+50088+Kuala+Lumpur%252C+Wilayah+Persekutuan./?state=Kuala+Lumpur" itemprop="addressRegion" title="Jalan Pinang, Kuala Lumpur City Centre, 50088 Kuala Lumpur, Wilayah Persekutuan.">
        Jalan Pinang, Kuala Lumpur City Centre, 50088 Kuala Lumpur, Wilayah Persekutuan.
        </a>
        ,
        <a class="" href="/search-results/?neighbourhood=Kuala+Lumpur&state=Kuala+Lumpur" title="Kuala Lumpur">
        Kuala Lumpur
        </a>
        ,
        <a class="" href="/search-results/?state=Kuala+Lumpur" title="Kuala Lumpur">
        Kuala Lumpur
        </a>
        <span class="" itemprop="postalCode">
            50088
        </span>
    </span>
    

    我想获取//span[@class='location']中的所有文本。

    1. response.xpath("//span[@class='location']//text()").extract_first()
    2. response.css("span.location *::text").extract_first()
    3. response.css("span.location ::text").extract_first()

    他们全都回来了 Mandarin Oriental Hotel

    编辑:

    吉隆坡市中心Jalan Pinang文华东方酒店,吉隆坡,吉隆坡威拉亚波斯库图,吉隆坡市中心,50088

    2 回复  |  直到 7 年前
        1
  •  3
  •   Andersson    7 年前

    尝试使用下面的代码来获取每个 span 地址:

    for entry in response.xpath("//div[@class='entry']"):
        print(entry.xpath("normalize-space(./span[@class='location'])").extract_first())
    
        2
  •  0
  •   vezunchik    7 年前

    response.css("span.location ::text").extract_first() 你只收到第一条短信,所以你可以试着打电话 response.css("span.location ::text").extract()

    您还可以尝试获取整个父元素并从中删除标记:

    from w3lib.html import remove_tags
    
    data = response.css('span.location').get()
    if not data:
        return
    result = remove_tags(data)
    
    推荐文章