【问题标题】:Python: How to turn two for-statements into one?Python:如何将两个 for 语句合二为一?
【发布时间】:2015-07-04 12:46:04
【问题描述】:

我正在尝试解析网络表格并将某些数据导出到 csv 文件中。

我不知道形成两个 XPath 后跟一个 for 语句(或者两个是正确的?)。

当前蜘蛛:

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

    def parse(self, response):
        hxs = HtmlXPathSelector(response)
        revenue = response.xpath('//td[@align="right"]/strong/text()')
        date = response.xpath('//tr[@class="yfnc_modtitle1"]/th/text()')
        items = []
        for rev in revenue:
            item = DozenItem()
            item["Revenue"] = rev.re('\d*,\d*')
            items.append(item)
        return items[:3]
        days = []
        for day in dates:
            item = DozenItem()
            item["Date"] = day.re('\d*')
            days.append(item)
        return items[:3]

我知道这需要工作,我只是不确定该往哪个方向发展...?

这是输出:

可见,我无法填写日期。

这是我解析日期的 html:

<TR class="yfnc_modtitle1" style="border-top:none;">

<th scope="col" style="border-top:2px solid #000;text-align:right; font-weight:bold">Dec 31, 2014</th>

<th scope="col" style="border-top:2px solid #000;text-align:right; font-weight:bold">Dec 31, 2013</th>
<th scope="col" style="border-top:2px solid #000;text-align:right; font-weight:bold">Dec 31, 2012</th>
</TR>
<tr>
<td colspan="2">

【问题讨论】:

    标签: python parsing csv export scrapy


    【解决方案1】:
    for rev, day in zip(revenue, dates):
        pass # code here
    

    【讨论】:

    • 这太棒了。我认为一定有办法做这样的事情,但不知道如何工作。
    【解决方案2】:
    class MySpider(BaseSpider):
        symbols = ["SCMP"]
        name =  "dozen"
        allowed_domains = ["yahoo.com"]     
        start_urls = ["http://finance.yahoo.com/q/is?s=SCMP&annual"]
    
        def parse(self, response):
            hxs = HtmlXPathSelector(response)
            revenue = response.xpath('//td[@align="right"]/strong/text()')
            date = response.xpath('//tr[@class="yfnc_modtitle1"]/th/text()')
            items = []
            for rev, day in zip(revenue, dates):
                item = DozenItem()
                item["Revenue"] = rev.re('\d*,\d*')
                item["Date"] = day.re('\d*')
                items.append(item)
            return items[:3]
    

    【讨论】:

    • zip() 是任意命名的,还是以某种方式特定于scrapy?它是否保持顺序?
    • zip 是内置的。 documentation 比我解释得更好。
    • The left-to-right evaluation order of the iterables is guaranteed. Python 文档。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-09
    • 1970-01-01
    • 1970-01-01
    • 2014-06-18
    • 2013-12-03
    • 1970-01-01
    相关资源
    最近更新 更多