Scrapy CSV导出在所有行中显示相同的数据

时间:2017-06-13 16:33:33

标签: scrapy scrapy-spider

我正在尝试抓取以下HTML代码:

<ul class="results-list" id="search-results">
<li>
<h3 class="name">First John</h3>
<div class="details">
<a href="mailto:example@mail.com" class="email">email</a>
&nbsp;
<span class="phone">999999999</span>
</div>
</li>
<li>
<h3 class="name">Second John</h3>
<div class="details">
<a href="mailto:example@mail.com" class="email">email</a>
&nbsp;
<span class="phone">999999999</span>
</div>
</li>
</ul>

当我运行我的蜘蛛时,我得到2行,包含相同的信息。我有名字,电子邮件,电话列,例如在名称栏中,我会得到: 第一约翰,第二约翰。

我的Scrapy代码如下:

people= response.xpath('//ul[@class="results-list"]/li')
        for person in people:
            item = SpiderItem()
            item['Name'] = person.xpath(
                '//h3/text()').extract()
            item['Email'] = person.xpath(
                '//div[@class="details"]/a/@href').extract()
            item['Phone'] = person.xpath(
                '//div[@class="details"]/span[@class="phone"]/text()').extract()
            yield item

但是,当我运行scrapy crawl MySpider -o output.csv时,我会在所有行中获得相同的信息。

1 个答案:

答案 0 :(得分:1)

您在xpath表达式上使用绝对路径,将它们更改为:

for person in people:
    item = SpiderItem()
    item['Name'] = person.xpath(
        './/h3/text()').extract_first()
    item['Email'] = person.xpath(
        './/div[@class="details"]/a/@href').extract_first()
    item['Phone'] = person.xpath(
        './/div[@class="details"]/span[@class="phone"]/text()').extract_first()
    yield item