Python: If 语句和 Scrapy XPath 选择器

Python: If statements and Scrapy XPath selector

我正在尝试 select table 最后一列中包含的值:https://ca.finance.yahoo.com/q/hp?s=bmo.TO&a=02&b=2&c=2005&d=02&e=2&f=2015&g=m

通常,这会很简单。类似于:

response.xpath('//table//table//tr[::6]/text()').extract()

但是,由于 yahoo 选择投入其中的这些红利行,第 n 个元素不断变化。但是,我注意到对于我想要 select 数据的每一行,第一个 td 包含:

Feb 2, 2015

而不是:

2015-01-29

因此,我正在尝试构建一个遵循逻辑的代码,如果 table 的第一个单元格包含任何字母,select 最后一列并将其附加到列表中。我的代码如下:

returns = []
trows = response.xpath('//table//table//tr')
for tr in trows:
      # don't know why I need to use "2" in the following line, but that's what gives me the first value.
    check = response.xpath('//td[2]/text()').extract()
    if any(c.isalpha() for c in check) == True:
        these = tr[6]
        returns.append(these)

这包含各种各样的问题,但我相信您可以想象得到。它给出了第一个 td 的值,它重复了与 table 中的 tr 一样多的次数。当我需要的最终结果是最后一个 td.

非常感谢收到的任何帮助!我正在尝试为金融 class 项目执行此操作以学习 python 而不是手动输入值。

干杯!

我会在 strptime() and exception handling. In other words, follow the EAFP principle.

的帮助下检查日期是否与 %b %d, %Y 格式匹配

来自 Scrapy Shell 的演示:

In [1]: from datetime import datetime
In [2]: rows = response.xpath('//table[@class="yfnc_datamodoutline1"]//table/tr')[1:]
In [3]: for row in rows:
            cells = row.xpath('.//td/text()').extract()
            try:
                datetime.strptime(cells[0], "%b %d, %Y")
                print cells[-1]
            except ValueError:
                continue    
77.15
77.46
72.93
81.33
82.99
80.88
...
44.12
42.46
39.00
42.20

我还改进了 XPath 表达式以更加关注所需的 table 数据。