开发者社区> 问答> 正文

python Tkinter和urllib2 脚本问题:报错

周末时写的一个可以自动提交BUG的脚本,主要是从excel中读取信息,然后自动保存到服务器上。最初是纯脚本,测试过执行没问题,功能也实现了。后来经理要求改成界面的,昨天看了下Tkinter,拼装了界面,也传了参数,但是就是提交不过去,一直报错:

Traceback (most recent call last):
  File "C:\Python27\lib\lib-tk\Tkinter.py", line 1410, in __call__
    return self.func(*args)
  File "tmp.py", line 56, in submit
    self.sbug(self.getck(who),source)
  File "tmp.py", line 108, in sbug
    self.headerBody(testUrl,list_2,sendheaders)
  File "tmp.py", line 137, in headerBody
    returnedResult=urllib2.urlopen(returnedReq).read()
  File "C:\Python27\lib\urllib2.py", line 126, in urlopen
    return _opener.open(url, data, timeout)
  File "C:\Python27\lib\urllib2.py", line 400, in open
    response = meth(req, response)
  File "C:\Python27\lib\urllib2.py", line 513, in http_response
    'http', request, response, code, msg, hdrs)
  File "C:\Python27\lib\urllib2.py", line 432, in error
    result = self._call_chain(*args)
  File "C:\Python27\lib\urllib2.py", line 372, in _call_chain
    result = func(*args)
  File "C:\Python27\lib\urllib2.py", line 619, in http_error_302
    return self.parent.open(new, timeout=req.timeout)
  File "C:\Python27\lib\urllib2.py", line 400, in open
    response = meth(req, response)
  File "C:\Python27\lib\urllib2.py", line 513, in http_response
    'http', request, response, code, msg, hdrs)
  File "C:\Python27\lib\urllib2.py", line 438, in error
    return self._call_chain(*args)
  File "C:\Python27\lib\urllib2.py", line 372, in _call_chain
    result = func(*args)
  File "C:\Python27\lib\urllib2.py", line 521, in http_error_default
    raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
HTTPError: HTTP Error 404: Not Found

下面我把脚本贴出来,大家帮忙看看是什么问题吧,多谢了。我是做测试的,之前自学过python的语法,也看过Django,不过都没实战。大家见谅。

#coding=utf-8
import sys as sys
import ttk as ttk
import Tix as tix
import Tkinter as Tk
import tkFileDialog
import xlrd
import urllib,urllib2

who = ''
source = ''
#row_list存储excel
row_list = []

#标题   描述   当前处理人  引入外网阶段   发现版本  分析和改进  抄送人 严重程度    测试改进方案    测试改进状态  外网问题
list_1=['data[Bug][title]','data[Bug][description]','data[Bug][current_owner]','data[Bug][custom_field_10]',
        'data[Bug][version_report]','data[Bug][custom_field_17]','data[Bug][cc]','data[Bug][severity]',
        'data[Bug][custom_field_16]','data[Bug][custom_field_19][]','data[Bug][custom_field_14][]']

dict1 = {'data[Bug][title]':0 ,'data[Bug][description]': 0,'data[Bug][current_owner]':0,'data[Bug][custom_field_10]':0,'data[Bug][version_report]':0,
         'data[Bug][custom_field_17]':0,'data[Bug][cc]':0,'data[Bug][severity]':0,'data[Bug][custom_field_16]':0,'data[Bug][custom_field_19][]':0,
         'data[Bug][custom_field_14][]':0}

class App:
    def __init__(self,root):
        self.win_ul = Tk.Frame(root,border=4)
        self.win_ul.pack(side='top',anchor='w')
        self.win_fp = Tk.Frame(root,border=4)
        self.win_fp.pack(side='top',anchor='w')
        self.win_ok = Tk.Frame(root,border=4)
        self.win_ok.pack(side='left',anchor='w')

        self.userLabel = Tk.StringVar(root,'xiaxinling')
        Tk.Label(self.win_ul,text='选择用户:'.decode('utf8')).pack(side='left')
        ttk.Combobox(self.win_ul,textvariable=self.userLabel,values=['xiaxinling','liujianyu','wu','wang'],width='12').pack(side='left')

        Tk.Label(self.win_fp,text='选择文件:'.decode('utf8')).pack(side='left')
        self.path_str = Tk.StringVar()
        Tk.Entry(self.win_fp,textvariable = self.path_str).pack()

        Tk.Button(self.win_ok, text = '浏览',command = self.FileOpen).pack(side='left')
        Tk.Button(self.win_ok, text="确定", command=self.submit).pack(side='right')
    def FileOpen(self):
        path = tkFileDialog.askopenfilename(title = 'Python Tkinter',      #创建打开文件对话框
            filetypes=[('execel', '*.xls'), ('All files', '*')] ) #指定文件类型
        global source
        source = path
        #global path_str
        self.path_str.set(source)
        print source
    def submit(self):
        who = str(self.userLabel.get().decode('utf8'))
        print "args,",who
        print "args,",source
        print "args,",self.getck(who)
        self.sbug(self.getck(who),source)
        #self.win_ul.quit
        #self.win_fp.quit
        #self.win_ok.quit
    def ShowArgs(self):
        who = str(self.userLabel.get().decode('utf8'))
        print "args,",who
        print "args,",source
        
    #提交bug单
    def sbug(self,ck,fp):
        print "sbug====%s ==%s" %(ck,fp)
        #下面是发帖验证
        #URL
        testUrl = 'http://rd.tencent.com/tapd/zizhu/bugtrace/bugs/submit/0?'
        #Cookie
        sendCookie = ck

        #发送的Headers,必须要有Cookie
        sendheaders = {
            'Host': 'rd.tencent.com',
            'Connection': 'keep-alive',
            'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.2 (KHTML,like Gecko) Explorer/9.0.8112.16421IC Chrome/15.0.874.121 Safari/535.2',
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
            'Accept-Encoding': 'gzip,deflate',
            'Accept-Language': 'zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3',
            'Accept-Charset': 'GBK,utf-8;q=0.7,*;q=0.3',
        }

        sendheaders['Cookie']=sendCookie
        
        #读取excel表单
        book = xlrd.open_workbook(fp)
        sheet=book.sheet_by_index(0)
        #行数
        nrows = sheet.nrows
        #print nrows
        
        for i in range(1,nrows):
            row_data = sheet.row_values(i)
            row_list.append(row_data)
       
        for e in row_list:
            i=0
            list_2=[]
            for s in e:
                dict1[list_1[i]]=s
                #print list_1[i]+':'+dict1[list_1[i]]
                list_2.append(s)
            print 'why'
            #print list_2[1]
            #发帖的data主体 list_2[0]
            self.headerBody(testUrl,list_2,sendheaders)

    #发帖的data主体
    def headerBody(self,testUrl,list_0,sendheaders):
        body=urllib.urlencode({'data[Bug][templates]':'1010030911010325971',
          'data[Bug][title]':'【外网缺陷】'+list_0[0],
          'data[Bug][issue_id]':'',
          'bug_id':'',
          'data[Bug][is_replicate]':'0',
          'data[Bug][create_link]':'0',
          'data[Bug][template_id]':'',
          'data[Bug][description]':list_0[1],
          'data[Bug][current_owner]':list_0[2], 
          'data[Bug][severity]':list_0[7],
          'data[Bug][custom_field_10]':list_0[3], 
          'data[Bug][custom_field_16]':list_0[8], 
          'data[Bug][version_report]':list_0[4],
          'data[Bug][version_fix]':'', 
          'data[Bug][custom_field_18][]':'否', 
          'data[Bug][custom_field_19][]':list_0[9], 
          'data[Bug][custom_field_17]':list_0[5], 
          'data[Bug][cc]':list_0[6],
          'data[Bug][custom_field_14][]':list_0[10],
          'data[save_draft]':'保存为草稿',
          'data[template_id]':'1010030911010325971',
          'data[draft_id]':'0', 
          'data[return_url]':'http://rd.tencent.com/tapd/zizhu/bugtrace/bugreports/my_view?auth_token=2b325ef17b9da69a6b042ce846242f776166521321104884d7d43aa4e206dc7798c66d9c1b0bd600|1&cur_bug_id='})
        returnedReq=urllib2.Request(url=testUrl,data=body,headers=sendheaders)
        print returnedReq
        returnedResult=urllib2.urlopen(returnedReq).read()
        #print returnedResult
        
    def getck(self,name):
        ck = ''
        f = open('cookie.txt')
        while True:
            line = f.readline()
            if line:
                parts = line.split(':')
                if parts[0].replace('\'','') == name:
                    ck = parts[1].replace('\'','').replace(',','')
            else:
                break
        f.close()
        return ck
    
def main():
    reload(sys)
    sys.setdefaultencoding("utf-8")
    root = Tk.Tk()
    root.title("AutoSubmit") # 添加标题
    root.geometry('300x100') # 设置大小
    app = App(root)
    root.mainloop()

if __name__ == "__main__":
    main()

展开
收起
kun坤 2020-06-07 21:36:39 678 0
1 条回答
写回答
取消 提交回答
  • 怎么都没有人回下啊。报404错,不过我不加GUI的时候URL是没有问题,加上GUI之后表单的信息都没动过....到底怎么个原因啊######找到问题了,原来是cookie最初写成了字典,换GUI后保存到了文件中,读取时自动给加上了\n。这个\n害我折腾了这么久
    ######
    ######厉害啊 看看路过

    2020-06-07 21:36:46
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
From Python Scikit-Learn to Sc 立即下载
Data Pre-Processing in Python: 立即下载
双剑合璧-Python和大数据计算平台的结合 立即下载