0

我正在尝试将 Ruby 语法转换为其等效的 Python:

这是Ruby代码:

collection_action :updateBackPlayers, :method => :get do

url="http://fantasyfootball.telegraph.co.uk/premierleague/select-team"
website = Nokogiri::HTML(open(url))

elements=website.xpath('//*[@id="list-GK"]/table/tr')

arr = []
elements.each do |row|
  x=row.xpath('td')
  name = x[0].text
  club = x[1].text
  @player=Player.find_by_name_and_club(name,club)
  arr=x[7].text.split("|")
  score=arr[1].split("/")   
  cards=arr[3].split("/") 
  clean_sheets = arr[2].split("/")
  goals=arr[4]

  weekly_points = arr[0].to_i - (@player.points || 0)

  @player.update_attributes(:weekly_points => weekly_points, :points => arr[0].to_i, :value=>x[2].text.to_f, :games=>score[0].to_i, :part_appearances=>score[1], :goals=>goals.to_i  )
  @player.update_attributes(:yellows=>cards[0], :reds=>cards[1], :clean_sheets=> clean_sheets[0], :part_clean_sheets=>clean_sheets[1]  )
  #@player.penalties_saved = arr[2]     
end 

这当然是使用 Nokogiri,但我想使用 lxml 和 XPath 做同样的事情,然后使用 SQLite3 将此信息保存在 Django 模型中。

这是Python代码。

 from lxml.html import parser
 url = "http://fantasyfootball.telegraph.co.uk/premierleague/select-team"
 website = parse(url)

 elements = website.xpath('//div[@id="list-GK"]//table/tr')

 for row in elements:
     x = row.xpath('td')
       for z in x:
         name = z[1].text
         club = z[2].text

但这不起作用,我得到一个超出限制的错误。我认为问题在于与 Python 中的elements.each do |row|不完全相同for row in elements:

我收到以下错误:

Traceback (most recent call last):
    File "<stdin>", line 3, in <module>
IndexError: list index out of range

但如果我这样做:

from lxml.html import parse
from fanaments.models import Player

url="http://fantasyfootball.telegraph.co.uk/premierleague/select-team"
page = parse(url)


elements = page.xpath('//div[@id="list-GK"]//table/tr')


for row in elements:
   x = row.xpath('td')
   for z in x:
        print z.text

我得到以下信息:

None
Hart, J
MCY
4.0
20
11.6%
None
Hart, Joe
MCY|£4.0m|5|0||20|0|0|0|4|0|0|3|0|0||||unknown|
MCY|£4.0m|39|0||140|1|0|0||0||18|0|1|||||
None
de Gea, D
MUN
3.9
15
6.4%
None
de Gea, David
MUN|£3.9m|5|0||15|0|0|0|6|0|0|2|0|0||||unknown|
MUN|£3.9m|33|0||99|0|0|0||0||11|0|0|||||

我怎样才能设法将名称保存为名称等?请帮助我已经被困在这太久了:)

4

0 回答 0