AttributeError: 'bytes'对象没有'timeout'属性

9 投票
3 回答
18254 浏览
提问于 2025-04-18 08:39
import re, urllib.request

textfile = open('depth_1.txt','wt')
print('enter the url you would like to crawl')
print('Usage - "http://phocks.org/stumble/creepy/" <-- with the double quotes')
my_url = input()
for i in re.findall(b'''href=["'](.[^"']+)["']''', urllib.request.urlopen(my_url).read(), re.I):
    print(i)
    for ee in re.findall(b'''href=["'](.[^"']+)["']''', urllib.request.urlopen(i).read(), re.I): #this is line 20!
        print(ee)
        textfile.write(ee+'\n')
textfile.close()

我在网上找了很久想解决我的问题,但没找到合适的办法。错误发生在第20行(AttributeError: 'bytes'对象没有'timeout'这个属性)。我对这个错误不是很理解,所以想找个答案和解释我哪里做错了。谢谢!

3 个回答

1

因为这是一个属性错误,说明你写的代码或者你使用的库中的某段代码试图访问一个对象的timeout属性。但是在你的情况下,传入的是一个字节对象,这可能就是问题所在。你可能在某个地方传错了对象类型。如果你确定你传递的对象是正确的,可以查看错误信息的追踪记录,看看timeout是在哪里被调用的,检查一下它期望是什么样的对象。

2

这个错误是因为你不能把字节串当作网址来用,检查一下你程序的编码设置。

8

来自文档关于urllib.request.urlopen的内容:

urllib.request.urlopen(url[, data][, timeout])

    Open the URL url, which can be either a string or a Request object.

如果urllib.request.urlopen没有收到一个字符串,它会认为你传入的是一个请求对象。你传入的是一个字节字符串,这就是出错的原因,比如:

>>> a = urllib.request.urlopen('http://www.google.com').read() # success
>>> a = urllib.request.urlopen(b'http://www.google.com').read() # throws same error
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/urllib/request.py", line 153, in urlopen
    return opener.open(url, data, timeout)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/urllib/request.py", line 446, in open
    req.timeout = timeout
AttributeError: 'bytes' object has no attribute 'timeout'

要解决这个问题,可以通过使用合适的解码方式把字节字符串转换回字符串:

>>> a = urllib.request.urlopen(b'http://www.google.com'.decode('ASCII')).read()

或者干脆不要使用字节字符串。

撰写回答