无法从父节点和子节点/标记中获取文本

2024-09-24 00:26:40 发布

您现在位置:Python中文网/ 问答频道 /正文

在标记为重复之前,我搜索并尝试了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,而不是完整地址。在

编辑: 文本应该屈服

Mandarin Oriental Hotel Jalan Pinang, Kuala Lumpur City Centre, 50088 Kuala Lumpur, Wilayah Persekutuan., Kuala Lumpur, Kuala Lumpur 50088


Tags: textcitygetlocationhotelcssclassspan
2条回答

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

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

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

相关问题 更多 >