【问题标题】:extract data from nested xpath从嵌套的 xpath 中提取数据
【发布时间】:2016-07-19 09:28:51
【问题描述】:

我是使用xpath的新手, 我想从this link中提取每个标题、正文、链接、发布日期

一切似乎都还好,但身体上没有,如何提取嵌套 xPath 上的每一个身体,谢谢 :)

这里是我的来源

from scrapy.spider import BaseSpider
from scrapy.selector import HtmlXPathSelector
from thehack.items import ThehackItem
class MySpider(BaseSpider):
    name = "thehack"
    allowed_domains = ["thehackernews.com"]
    start_urls = ["http://thehackernews.com/search/label/mobile%20hacking"]
    def parse(self, response):
        hxs = HtmlXPathSelector(response)
        titles = hxs.xpath('//article[@class="post item module"]')
        items = []
        for titles in titles:
            item = ThehackItem()
            item['title'] = titles.select('span/h2/a/text()').extract()
            item['link'] = titles.select('span/h2/a/@href').extract()
        item['body'] = titles.select('span/div/div/div/div/a/div/text()').extract()
        item['date'] = titles.select('span/div/span/text()').extract()
            items.append(item)
        return items

任何人都可以修复身体块?只在身体... 先谢谢队友 这里是来自网站的检查元素图片

【问题讨论】:

  • 'body' 需要解决什么问题?你得到什么?你在期待什么?
  • 我想得到这篇文章的主要内容,讨论什么文章……但是我什么都得不到,伙计
  • 你能帮我保罗吗?

标签: python xpath scrapy web-crawler


【解决方案1】:

我认为你在与选择器作斗争,对吧?我认为您应该查看selectors 的文档,那里有很多很好的信息。在这个特定的例子中,使用 css 选择器,我认为它会是这样的:

class MySpider(scrapy.Spider):
    name = "thehack"
    allowed_domains = ["thehackernews.com"]
    start_urls = ["http://thehackernews.com/search/label/mobile%20hacking"]

    def parse(self, response):
        for article in response.css('article.post'):
            item = ThehackItem()
            item['title'] = article.css('.post-title>a::text').extract_first()
            item['link'] = article.css('.post-title>a::attr(href)').extract_first()
            item['body'] = ''. join(article.css('[id^=summary] *::text').extract()).strip()
            item['date'] = article.css('[itemprop="datePublished"]::attr(content)').extract_first()
            yield item

将它们更改为 xpath 选择器对您来说是一个很好的练习,也许还可以检查ItemLoaders,它们一起非常有用。

【讨论】:

  • 你帮我弄到paragprah mate的正文内容?
猜你喜欢
  • 1970-01-01
  • 2020-07-30
  • 1970-01-01
  • 2020-04-19
  • 2020-06-28
  • 1970-01-01
  • 2021-06-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多