URL解析仅工作于显式

2024-09-25 10:27:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我从一个.csv文件中读取URL,并试图解析它们。为什么当我在函数urlparse(...)中显式地放置链接时,我只能在schemenetloc中得到正确的值,请参见变量o2,而在urlparse中给出newsource时却得不到正确的值

for line in file:
    source = str(line.split(",")[2])
    print("ORIGINAL URL: \n" + source)
    newsource = source.replace('"',"")
    print("REMOVING QUOTES: \n" + newsource)
    newsource.strip
    print("STRIPPING SPACES: \n" + newsource + "\n")
    o = urlparse(newsource)
    print("RESULT PARSING: " + str(o) + "\n")
    o2 = urlparse("http://nl.aldi.be/aldi_vlees_609.html")
    print("RESULT MANUAL PARSING: " + str(o2) + "\n")

输出: enter image description here


Tags: 文件csv函数urlsource链接lineresult
1条回答
网友
1楼 · 发布于 2024-09-25 10:27:41

我可以从失败的解析中看出,您有一个前导空格字符,这将导致与您相同的问题:

>>> urlparse.urlparse(' http://nl.aldi.be/aldi_vlees_609.html')
ParseResult(scheme='', netloc='', path=' http://nl.aldi.be/aldi_vlees_609.html', params='', query='', fragment='')

此行不起任何作用:

newsource.strip

你可能想要:

newsource = newsource.strip()

相关问题 更多 >