【发布时间】:2015-06-11 01:11:00
【问题描述】:
所以我要抓取的表可以在这里找到:http://www.betdistrict.com/tipsters
我关注的是名为“六月统计”的表格。
这是我的蜘蛛:
from __future__ import division
from decimal import *
import scrapy
import urlparse
from ttscrape.items import TtscrapeItem
class BetdistrictSpider(scrapy.Spider):
name = "betdistrict"
allowed_domains = ["betdistrict.com"]
start_urls = ["http://www.betdistrict.com/tipsters"]
def parse(self, response):
for sel in response.xpath('//table[1]/tr'):
item = TtscrapeItem()
name = sel.xpath('td[@class="tipst"]/a/text()').extract()[0]
url = sel.xpath('td[@class="tipst"]/a/@href').extract()[0]
tipster = '<a href="' + url + '" target="_blank" rel="nofollow">' + name + '</a>'
item['Tipster'] = tipster
won = sel.xpath('td[2]/text()').extract()[0]
lost = sel.xpath('td[3]/text()').extract()[0]
void = sel.xpath('td[4]/text()').extract()[0]
tips = int(won) + int(void) + int(lost)
item['Tips'] = tips
strike = Decimal(int(won) / tips) * 100
strike = str(round(strike,2))
item['Strike'] = [strike + "%"]
profit = sel.xpath('//td[5]/text()').extract()[0]
if profit[0] in ['+']:
profit = profit[1:]
item['Profit'] = profit
yield_str = sel.xpath('//td[6]/text()').extract()[0]
yield_str = yield_str.replace(' ','')
if yield_str[0] in ['+']:
yield_str = yield_str[1:]
item['Yield'] = '<span style="color: #40AA40">' + yield_str + '%</span>'
item['Site'] = 'Bet District'
yield item
这给了我第一个变量(名称)的列表索引超出范围错误。
但是,当我重写以 // 开头的 xpath 选择器时,例如:
name = sel.xpath('//td[@class="tipst"]/a/text()').extract()[0]
蜘蛛跑了,但一遍又一遍地刮掉第一个提示者。
我认为这与没有thead但在tbody的第一个tr内包含th标签的表格有关。
非常感谢任何帮助。
---------编辑----------
回应拉斯的建议:
我已尝试使用您的建议,但仍然出现列表超出范围错误:
from __future__ import division
from decimal import *
import scrapy
import urlparse
from ttscrape.items import TtscrapeItem
class BetdistrictSpider(scrapy.Spider):
name = "betdistrict"
allowed_domains = ["betdistrict.com"]
start_urls = ["http://www.betdistrict.com/tipsters"]
def parse(self, response):
for sel in response.xpath('//table[1]/tr[td[@class="tipst"]]'):
item = TtscrapeItem()
name = sel.xpath('a/text()').extract()[0]
url = sel.xpath('a/@href').extract()[0]
tipster = '<a href="' + url + '" target="_blank" rel="nofollow">' + name + '</a>'
item['Tipster'] = tipster
yield item
另外,我假设通过这种方式,需要多个 for 循环,因为并非所有单元格都具有相同的类?
我也尝试过不使用 for 循环来做事,但在这种情况下,它又一次只抓取了第一个提示者多次:s
谢谢
【问题讨论】: