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

时间:2018-11-13 09:35:38

标签: python xpath web-scraping scrapy

在将此标记为重复之前,我已经搜索并尝试了在SO上找到的其他解决方案,这些解决方案是:

  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

我要从中提取的HTML是:

<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吉隆坡,威拉雅柏苏安。,吉隆坡,吉隆坡50088

2 个答案:

答案 0 :(得分:1)

尝试使用以下代码获取每个span的地址的字符串表示形式:

for entry in response.xpath("//div[@class='entry']"):
    print(entry.xpath("normalize-space(./span[@class='location'])").extract_first())

答案 1 :(得分:0)

使用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)