【问题标题】:Python list object has no attribute errorPython列表对象没有属性错误
【发布时间】:2017-06-19 05:25:52
【问题描述】:

我是 Python 新手,我正在尝试编写一个网站爬虫来从 subreddits 获取链接,然后我可以稍后将其传递给另一个类,以便从 imagur 自动下载图像。

在这段代码 sn-p 中,我只是试图读取 subreddit 并从 hrefs 中抓取任何 imagur html,但我收到以下错误:

AttributeError: 'list' object has no attribute 'timeout'

知道为什么会发生这种情况吗?代码如下:

from bs4 import BeautifulSoup
from urllib2 import urlopen
import sys
from urlparse import urljoin

def get_category_links(base_url):
    url = base_url
    html = urlopen(url)
    soup = BeautifulSoup(html)
    posts = soup('a',{'class':'title may-blank loggedin outbound'})
    #get the links with the class "title may-blank "
    #which is how reddit defines posts
    for post in posts:
        print post.contents[0]
        #print the post's title

        if post['href'][:4] =='http':
            print post['href']
        else:
            print urljoin(url,post['href'])
        #print the url.  
        #if the url is a relative url,
        #print the absolute url.   


get_category_links(sys.argv)

【问题讨论】:

  • 要么发布完整的回溯,要么提及行号。
  • 你在 urlopen 上使用了.read() 吗?
  • 请发布完整的错误消息,包括回溯。该错误不是由您的代码直接引起的,它来自您正在使用的库之一。

标签: python list web-scraping


【解决方案1】:

看看你是怎么调用函数的:

get_category_links(sys.argv)

sys.argv 这是脚本参数列表,其中第一项是脚本名称本身。这意味着您的 base_url 参数值是一个导致 urlopen 失败的列表:

>>> from urllib2 import urlopen
>>> urlopen(["I am", "a list"])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 154, in urlopen
    return opener.open(url, data, timeout)
           │           │    │     └ <object object at 0x105e2c120>
           │           │    └ None
           │           └ ['I am', 'a list']
           └ <urllib2.OpenerDirector instance at 0x105edc638>
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 422, in open
    req.timeout = timeout
    │             └ <object object at 0x105e2c120>
    └ ['I am', 'a list']
AttributeError: 'list' object has no attribute 'timeout'

您的意思是从sys.argv 获取第二个参数并将其传递给get_category_links

get_category_links(sys.argv[1])

有趣的是,这种情况下的错误是多么神秘和难以理解。这是来自"url opener" works in Python 2.7 的方式。如果url 值(第一个参数)不是字符串,则假定它是Request 实例并尝试在其上设置timeout 值:

def open(self, fullurl, data=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
    # accept a URL or a Request object
    if isinstance(fullurl, basestring):
        req = Request(fullurl, data)
    else:
        req = fullurl
        if data is not None:
            req.add_data(data)

    req.timeout = timeout  # <-- FAILS HERE

注意behavior have not actually changed in the latest stable 3.6 as well

【讨论】:

  • 您能否在您的回答中分享如何像您的一样漂亮地打印回溯?谢谢。
  • @zhenguoli 当然,这是better-exceptions 项目,很酷很方便。谢谢。
  • 非常感谢。你真好。
猜你喜欢
  • 2021-12-04
  • 1970-01-01
  • 1970-01-01
  • 2021-05-25
  • 2022-01-20
  • 1970-01-01
  • 2014-05-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多