Scrapy项目,刮取时间表

时间:2013-09-13 20:01:24

标签: python xpath web-scraping scrapy

所以我试图在这个页面上缩短时间表.. http://stats.swehockey.se/ScheduleAndResults/Schedule/3940

..使用此代码。

from scrapy.spider import BaseSpider
from scrapy.selector import HtmlXPathSelector

class SchemaSpider(BaseSpider):
    name = "schema"
    allowed_domains = ["http://stats.swehockey.se/"]
    start_urls = [
        "http://stats.swehockey.se/ScheduleAndResults/Schedule/3940"
    ]

def parse(self, response):
    hxs = HtmlXPathSelector(response)
    rows = hxs.select('//table[@class="tblContent"]/tbody/tr')

    for row in rows:
        date = row.select('/td[1]/div/span/text()').extract()
        teams = row.select('/td[2]/text()').extract()

        print date, teams

但我无法让它发挥作用。我究竟做错了什么?我一直试图弄清楚自己几个小时但我不知道为什么我的XPath不能正常工作。

1 个答案:

答案 0 :(得分:1)

两个问题:

  • tbody是由现代浏览器添加的标记。 Scrapy根本没有在html中看到它。

  • 数据和团队的xpaths不正确:你应该使用相对xpath(.//),td索引也是错误的,应该是2和3而不是1和2

    < / LI>

这是整个代码与一些mofidications(工作):

from scrapy.item import Item, Field
from scrapy.spider import BaseSpider
from scrapy.selector import HtmlXPathSelector


class SchemaItem(Item):
    date = Field()
    teams = Field()


class SchemaSpider(BaseSpider):
    name = "schema"
    allowed_domains = ["http://stats.swehockey.se/"]
    start_urls = [
        "http://stats.swehockey.se/ScheduleAndResults/Schedule/3940"
    ]

    def parse(self, response):
        hxs = HtmlXPathSelector(response)
        rows = hxs.select('//table[@class="tblContent"]/tr')

        for row in rows:
            item = SchemaItem()
            item['date'] = row.select('.//td[2]/div/span/text()').extract()
            item['teams'] = row.select('.//td[3]/text()').extract()

            yield item

希望有所帮助。