簡體   English   中英

'ValueError: 未知 url 輸入' tkinter 和 urllib

[英]'ValueError: unknown url type in' tkinter and urllib

看起來我錯過了一些非常關鍵的東西。 即使在 GUI window 彈出或單擊按鈕之前,我也收到此錯誤。

當我在條目中輸入數據時,它應該將其傳遞到“url_link”上,該“url_link”會在“get_data_url”中進一步傳遞。 'get_data_url' function 應該在按下按鈕后執行,但它是在開始時執行的。 我不確定這里有什么問題。

Traceback (most recent call last):
  File "gui.py", line 100, in <module>
    btn1 = Button(win, text="Submit", command = get_data_url(url_link))
  File "gui.py", line 50, in get_data_url
    req = Request(url_link, headers={'User-Agent': 'Mozilla/5.0'})
  File "/usr/lib/python3.8/urllib/request.py", line 328, in __init__
    self.full_url = url
  File "/usr/lib/python3.8/urllib/request.py", line 354, in full_url
    self._parse()
  File "/usr/lib/python3.8/urllib/request.py", line 383, in _parse
    raise ValueError("unknown url type: %r" % self.full_url)
ValueError: unknown url type: '/wp-json/wp/v2/posts/?per_page=100'

我的代碼 -

##GUI
import tkinter as tk
from tkinter import messagebox
from tkinter import *
win = tk.Tk()


win.geometry("300x200")
#Label
label = Label(text="URL - ")
label.place(x=20, y=50)
#Entry
entry1 = tk.Entry()
entry1.place(x=70, y=50)



#Execution

##MainCode
import os
import csv
import json
import sys
import requests
import urllib
from urllib.request import Request, urlopen, HTTPError
from urllib.parse import urlparse
import argparse

parser = argparse.ArgumentParser()
parser.add_argument('-f', '--file', help='To mention file')
parser.add_argument('-u', '--url', help='Passing one url')
parser.add_argument('-p', '--pages', action='store_true', help='To download pages/post')
args = parser.parse_args()


def get_urls(filename):
    urls = []

    file = open(filename, "r")

    for i in file:
        i = i.replace("\n", "")
        urls.append(i)
    return urls

def get_data_url(url_link):
    req = Request(url_link, headers={'User-Agent': 'Mozilla/5.0'})
    webpage = urlopen(req).read()
    ## Fetching hostname of the URL
    parsed_uri = urlparse(url_link)
    result = '{uri.netloc}'.format(uri=parsed_uri)
    print(result)
    # Write data to file
    filename = "data/" + result + "-raw.txt"
    file_ = open(filename, 'wb')
    file_.write(webpage)
    file_.close()


    with open(filename) as json_file:
        json_data = json.load(json_file)

    C_data = []

    for n in json_data:  
    
        r={}
        r["Modified"] = n['modified']
        r["Title"] = n['title']['rendered']
        r["Content"] = n['content']['rendered']
        r["Link"] = n['link']

        # JSON Conversion

        j_data = {
            "modified/posted" : r["Modified"],
            "title" : r["Title"],
            "content" : r["Content"],
            "link" : r["Link"]
        }

        C_data.append(j_data)
        print("Title: " + r["Title"])
        print("Status: Downloaded")
        
    json_object = json.dumps(C_data, indent = 4) 

    # Writing to sample.json 
    with open("data/" + result + "-data.json", "w") as outfile: 
        outfile.write(json_object)
    print("Extracted Successfully")

urlhere = entry1.get()    
url_link = urlhere + "/wp-json/wp/v2/posts/?per_page=100"

#Button

btn1 = Button(win, text="Submit", command = get_data_url(url_link))
btn1.place(x=90, y=80)
win.mainloop()

您應該在提交按鈕的回調中獲取Entry的內容,構造 URL 並調用get_data_url()

def submit():
    urlhere = entry1.get()    
    url_link = urlhere + "/wp-json/wp/v2/posts/?per_page=100"
    get_data_url(url_link)

btn1 = Button(win, text="Submit", command=submit)

該錯誤可能是由於事件驅動編程,您在運行時分配url_here的值,這意味着它將是空的(因為該框一開始是空的),因此要修復它,將其移動到 function 內部,例如:

# Same code

def get_data_url():
    urlhere = entry1.get()    
    url_link = urlhere + "/wp-json/wp/v2/posts/?per_page=100"

    req = Request(url_link, headers={'User-Agent': 'Mozilla/5.0'})
    webpage = urlopen(req).read()
    ## Fetching hostname of the URL
    .... # Same code    

btn1 = Button(win, text="Submit", command=get_data_url)

您可以擺脫該參數,因為您不必再使用它了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM