【问题标题】:Unable to get text from parent and child nodes/tags with Scrapy无法使用 Scrapy 从父节点和子节点/标签获取文本
【发布时间】:2019-04-16 02:28:28
【问题描述】:

在这被标记为重复之前,我已经搜索并尝试了在 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

【问题讨论】:

  • 我不是 Scrapy 用户,但我想这是因为您使用的是 extract_first。试试" ".join(response.xpath("//span[@class='location']//text()").extract())
  • @Andersson 不幸的是,这将产生页面中所有单个项目的地址。页面:hungrygowhere.my/search-results/?search_location=Kuala+Lumpur
  • 您的意思是将所有地址作为单个字符串返回,并且您希望每个结果都有单独的地址?

标签: python xpath web-scraping scrapy


【解决方案1】:

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

【讨论】:

  • .extract() 将获得完整地址,但它还将获得页面中每个条目/项目的所有其他地址。我想要每个条目/项目的完整个人地址。
【解决方案2】:

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

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

【讨论】:

  • 谢谢,这行得通。我不得不从第一行删除 .extract() 。 for entry in response.xpath("//div[@class='entry']"): print(entry.xpath("normalize-space(./span[@class='location'])").extract_first())
  • @AmirAsyraf,哦,对了。感谢您纠正我...答案已更新
猜你喜欢
  • 2015-03-30
  • 2014-12-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多