2013-06-11 2 views
0

매우 간단한 디버깅 질문이 될 수 있습니다. (필자는 고독하지 않습니다.) 긁힌 XML을 구문 분석하는 루핑 코드가 있지만이 구문 분석은 5 분 루프에서 발생하지만 doesn은 아닙니다. 하나의 루프에서 다음 루프로 중복을 반환하지 않습니다. 사용자 ID를 세트에 저장 한 결과로, 사용자 ID가 이미 userset에 존재하면 스크립트는 XML의 다음 행으로 건너 뜁니다. 이 스크립트의 결과를 RSS로 출력하고 싶습니다. 그러나 그렇게 할 수있는 잠재적 방법론이 있습니다. 그러나 먼저 데이터를 일종의 변수로 저장해야합니다.RSS 피드에 입력 할 변수를 생성합니다.

나는이 작업을 시도했으나 매번 마지막 세트의 사용자 ID가 문제가되는 것으로 보입니다. 깨진 코드를 제공하는 대신 출력 코드를 변수로 정의하려는 내 해쉬 시도를 포함하지 않는 작업 코드 예제를 묶습니다.

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

######Code to loop the script and set up scheduling time 

s = scheduler(time, sleep) 
random.seed() 

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

###### Code to get the data required from the URL desired 
def getData(): 
    post_url = "URL OF INTEREST" 
    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' : '250', 
       '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>') 

##### Making the code identify each row, removing the need to numerically quantify the  number of rows in the xmlfile, 
##### thus making number of rows dynamic (change as the list grows, required for looping function to work un interupted) 

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

##### defining the Keys (key is the area from which data is pulled in the XML) for use in the pattern finding/regex 

     user_delimiter = cell['username'] 
     selection_delimiter = cell['race_horse'] 

     if strikeratecalc2 < 12 : continue; 

##### REMAINDER OF THE REGEX DELMITATIONS 

     username_delimiter_results = re.findall(pattern1, user_delimiter)[0] 
     userid_delimiter_results = (re.findall(pattern2, user_delimiter)[0]) 
     user_selection = re.findall(pattern3, selection_delimiter)[0] 

##### Code to stop duplicate posts of each user throughout the day 

    userset = set ([]) 
    if userid_delimiter_results in userset: continue; 

##### Printing the results of the code at hand 

     print "user id = ",userid_delimiter_results 
     print "username = ",username_delimiter_results 
     print "user selection = ",user_selection 
     print "" 

##### Code to stop duplicate posts of each user throughout the day part 2 (udating set to add users already printed to the ignore list) 

    userset.update(userid_delimiter_results) 

    getData() 

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

변수를 생성 할 때 내가 가진 문제 든 코드가 마지막 userset.update (userid_delimiter_results)을 잃어버린 것은 이것이 마지막 항목으로 이어진했다 (I 배열로 생산하기 위해 노력했다) 'userset'에 따라 문제의 사용자 ID가 기록되지 않았기 때문에 코드가 실행될 때마다 피드가 반복됩니다. 이 코드의 결과를 변수로 출력 할 수있는 간단한 방법은 크게 감사하겠습니다. 친절한 대답 AEA

+0

근무 수많은 문제가 있습니다. 예를 들어, 코드가 항상 빈 집합 (userset)에 대해 테스트하려고하면 테스트 자체가 잘못 될 수 있습니다 (또는 userset.update()에 대한 이후 호출이 잘못됨). run_periodically cal l은 무한 재귀 (getData())로 인해 도달 할 수 없습니다. 작은 조각으로 코드를 분할하고 각각의 평화가 정확히 무엇을하는지 이해할 때까지 모의 데이터로 개별적으로 테스트하십시오. [scrapy] (http://doc.scrapy.org/en/latest/intro/overview.html)를 사용하여 크롤링, 데이터 긁기, 피드 생성 또는 [scrapely] (https://github.com/scrapy)를 고려하십시오./scrapely) html에서 데이터를 추출합니다. – jfs

답변

1

인쇄 섹션을 만들어서이 작업을 수행했습니다.

arrayna = [arrayna1, arrayna2, arrayna3, arrayna4] 

    arraym1 = "user id = ",userid_delimiter_results 

그런 얼굴을 극복하기 위해 루프 arrayna의 각 실행에 그

my_array = [] # Create an empty list 

print(my_array) 

그래서 코드가 같은 것을 볼 수있을 것이다 :

을이 :)

관련 문제