【发布时间】:2022-01-05 22:58:27
【问题描述】:
这个程序已经运行了多年。我好几个月没用了,现在它不会下载必要的文件了。我在 Windows 7 上使用 python37。 将字节解码为字符串还有一个新问题。
这是相关的子程序,带有注释:
import urllib
import urllib.request
import socket
import sys, os
# ---
def geturl(url, stk): # reads a web page into a string
print("at180: into geturl with url=",url)
#Here's the url I passed it
#https://finance.yahoo.com/quote/qqq/history?period1=1480204800&period2=1637971200&interval=1mo&filter=history&frequency=1mo
# it returns a 404 error, but works fine if pasted into Chrome browser, or when used in a perl call to get.
# I tried a simpler one: https://finance.yahoo.com/quote/QQQ/history?p=QQQ
url = "https://finance.yahoo.com/quote/QQQ/history?p=QQQ"
# it also returned a 404 error
#I tried one even simpler
url = "https://finance.yahoo.com"
# this one does not return a 404 error but has conversion error from byte to str
try:
junk = urllib.request.urlopen(url, timeout=4).read()
except urllib.error.URLError as e:
print("URLError with ",stk," = ", e)
return("Error")
except socket.timeout as e:
return("Timeout")
page = str( junk, encoding='utf8' ) # convert from type 'bytes' to type 'str
# error here with the simple url:
"UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8b in position 1: invalid start byte "
print("\nat197, returning page")
pause()
return(page)
为什么 urllib.request.urlopen 找不到一个如果传递给 Chrome 浏览器可以正常工作的 url?
如果我除了基本 url 地址之外的所有内容都省略了,为什么它会找到它?
如何打印出字节字符串“垃圾”以便阅读? 它似乎有很多非十六进制字符。
网页不再使用 UTF-8 了吗?如果是这样,我应该指定什么编码?
【问题讨论】:
-
您是否尝试过使用 requests 库? (只是看看你能不能从那个网址得到一些东西)
-
很有可能,finance.yahoo.com 现在正在阻止基于用户代理的 python 请求。
-
如果您还有其他问题,请随时在下方回复 - 如果您认为您的问题已得到解答,您可以接受带有复选标记的答案,它会在网站上显示为已回答。
标签: python download file-conversion