大家好,感谢您抽出宝贵的时间来研究我的问题,我已经在此代码上工作了大约1周(我也是编码和python的新手,也是1周的时间)。目前,该循环仅在xrange(x)中有效和'rp':'x'是该xml中可用的正确行数。 xml整天更新,我想知道是否有人可以提供使x动态的解决方案?

import mechanize
import urllib
import json
import re
from sched import scheduler
from time import time, sleep

from sched import scheduler
from time import time, sleep

s = scheduler(time, sleep)

def run_periodically(start, end, interval, func):
event_time = start
while event_time < end:
    s.enterabs(event_time, 0, func, ())
    event_time += interval
s.run()

def getData():
post_url = "urlofinterest_xml"
browser = mechanize.Browser()
browser.set_handle_robots(False)
browser.addheaders = [('User-agent', 'Firefox')]

######These are the parameters you've got from checking with the aforementioned tools
parameters = {'page' : '1',
              'rp' : '8',
              'sortname' : 'roi',
              'sortorder' : 'desc'
             }
#####Encode the parameters
data = urllib.urlencode(parameters)
trans_array = browser.open(post_url,data).read().decode('UTF-8')

xmlload1 = json.loads(trans_array)
pattern1 = re.compile('>&nbsp;&nbsp;(.*)<')
pattern2 = re.compile('/control/profile/view/(.*)\' title=')
pattern3 = re.compile('<span style=\'font-size:12px;\'>(.*)<\/span>')
pattern4 = re.compile('title=\'Naps posted: (.*) Winners:')
pattern5 = re.compile('Winners: (.*)\'><img src=')


for i in xrange(8):
    user_delimiter = xmlload1['rows'][i]['cell']['username']
    selection_delimiter = xmlload1['rows'][i]['cell']['race_horse']

    username_delimiter_results = re.findall(pattern1, user_delimiter)[0]
    userid_delimiter_results = int(re.findall(pattern2, user_delimiter)[0])
    user_selection = re.findall(pattern3, selection_delimiter)[0]
    user_numberofselections = float(re.findall(pattern4, user_delimiter)[0])
    user_numberofwinners = float(re.findall(pattern5, user_delimiter)[0])

    strikeratecalc1 = user_numberofwinners/user_numberofselections
    strikeratecalc2 = strikeratecalc1*100

    print "user id = ",userid_delimiter_results
    print "username = ",username_delimiter_results
    print "user selection = ",user_selection
    print "best price available as decimal = ",xmlload1['rows'][i]['cell']     ['tws.best_price']
    print "race time = ",xmlload1['rows'][i]['cell']['race_time']
    print "race meeting = ",xmlload1['rows'][i]['cell']['race_meeting']
    print "ROI = ",xmlload1['rows'][i]['cell']['roi']
    print "number of selections = ",user_numberofselections
    print "number of winners = ",user_numberofwinners
    print "Strike rate = ",strikeratecalc2,"%"
    print ""


getData()


run_periodically(time()+5, time()+1000000, 15, getData)


亲切的问候AEA

最佳答案

首先,我将讨论您如何迭代结果。根据您的代码,xmlload1['rows']是一个字典数组,因此您可以直接在其上进行迭代,而不是选择一个任意数字。为了使这个例子更好,我将设置一些任意数据以使这一点变得清楚:

xmlload1 = {
   "rows": [{"cell": {"username": "one", "race_horse":"b"}}, {"cell": {"username": "two", "race_horse": "c"}}]
}


因此,根据上述数据,您可以像这样循环遍历for循环中的行:

for row in xmlload1['rows']:
    cell = row["cell"]
    print cell["username"]
    print cell["race_horse"]


每次迭代时,单元格都会获取可迭代对象(xmlload1['rows']中的列表)中另一个元素的值。这适用于支持迭代的任何容器或序列(例如liststuplesdictsgenerators等)

请注意,我在任何地方都没有使用任何幻数,因此xmlload1['rows']可以任意长,并且仍然可以使用。

您可以使用以下函数将请求设置为动态请求:

def get_data(rp=8, page=1):
    parameters = {'page' : str(page),
              'rp' : str(rp),
              'sortname' : 'roi',
              'sortorder' : 'desc'
             }
    data = urllib.urlencode(parameters)
    trans_array = browser.open(post_url,data).read().decode('UTF-8')
    return json.loads(trans_array)


现在,您可以调用get_data(rp=5)以获得5行,或者调用get_data(rp=8)以获得8行[并且get_data(rp=8, page=3)获得第三页],依此类推。您可以清楚地添加其他变量,甚至可以传入parameters直接决定功能。

10-07 17:00