簡體   English   中英

Python:Scrapy導出原始數據而不是僅導出text()嗎?

[英]Python: Scrapy exports raw data instead of text() only?

我正在從此類中導出:

class MySpider(BaseSpider):
    name =  "dozen"
    allowed_domains = ["yahoo.com"]
    start_urls = ["http://finance.yahoo.com/q/is?s=SCMP+Income+Statement&annual"]

    def parse(self, response):
        hxs = HtmlXPathSelector(response)
        revenue = hxs.select('//td[@align="right"]')
        items = []
        for rev in revenue:
            item = DozenItem()
            item["Revenue"] = rev.xpath("./strong/text()")
            items.append(item)
        return items[:7]

並得到這個:

[<HtmlXPathSelector xpath='./strong/text()' data=u'\n                            115,450\xa0\xa0\n '>]

但是我只想要115,450

如果將.extract()添加到item["Revenue"]行的末尾,則不會輸出任何內容。

這是html的部分,其中包括我要嘗試抓取的內容:

<tr>
<td colspan="2">
<strong>Total Revenue</strong>
</td>
<td align="right">
<strong>115,450&nbsp;&nbsp;</strong>
</td>
<td align="right">
<strong>89,594&nbsp;&nbsp;</strong>
</td>
<td align="right">
<strong>81,487&nbsp;&nbsp;</strong>
</td>
</tr>

您嘗試對第一個選擇使用過於寬泛的Xpath表達式。 像這樣嘗試:

def parse(self, response):
    revenue = response.xpath('//td[@align="right"]/strong/text()')
    items = []
    for rev in revenue:
        item = DozenItem()
        item["Revenue"] = rev.re('\d*,\d*')
        items.append(item)
    return items[:3]

我覺得你過得不錯。 可以顯示html嗎?

通常,我使用以下代碼:

rev.xpath("./strong/text()").extract()[0].encode('utf8').strip()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM