【问题标题】:AttributeError: 'bytes' object has no attribute 'data'AttributeError:“字节”对象没有属性“数据”
【发布时间】:2014-12-14 19:59:15
【问题描述】:

这个脚本的目的是使用python登录一个网站,登录并通过

使用登录启动脚本并作为参数传递。

[vegasus@Ph3NyX:~]$python3 grabbit.py mylogin mypass

Traceback (most recent call last):
  File "/Users/vegasus/PycharmProjects/Lesson_Python/grabbit.py", line 102, in <module>
    WebLogin('mylogin', 'mypass')
  File "/Users/vegasus/PycharmProjects/Lesson_Python/grabbit.py", line 61, in __init__
    response = self.login()
  File "/Users/vegasus/PycharmProjects/Lesson_Python/grabbit.py", line 82, in login
    response = self.opener.open(login_url.encode(), login_data.encode())
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/urllib/request.py", line 444, in open
    req.data = data
AttributeError: 'bytes' object has no attribute 'data'

这是脚本:

import urllib, urllib.request, urllib.parse
import http.cookiejar
import sys

class WebLogin(object):

    def __init__(self, username, password):

        # url for website we want to log in to
        self.base_url = 'https://www.mywebsite.com'
        # login action we want to post data to
        # could be /login or /account/login or something similar
        self.login_action = '/en/login'
        # file for storing cookies
        self.cookie_file = 'login.cookies'

        # user provided username and password
        self.username = username
        self.password = password

        # set up a cookie jar to store cookies
        self.cj = http.cookiejar.MozillaCookieJar(self.cookie_file)

        # set up opener to handle cookies, redirects etc
        self.opener = urllib.request.build_opener(
            urllib.request.HTTPRedirectHandler(),
            urllib.request.HTTPHandler(debuglevel=0),
            urllib.request.HTTPSHandler(debuglevel=0),
            urllib.request.HTTPCookieProcessor(self.cj)
        )

        # pretend we're a web browser and not a python script
        self.opener.addheaders = [('User-agent',
            ('Mozilla/4.0 (compatible; MSIE 6.0; '
            'Windows NT 5.2; .NET CLR 1.1.4322)'))
        ]

        # open the front page of the website to set and save initial cookies
        response = self.opener.open(self.base_url)
        self.cj.save()

        # try and log in to the site
        response = self.login()

        print (response.read())

    # method to do login
    def login(self):

        # parameters for login action
        # may be different for different websites
        # check html source of website for specifics
        login_data = urllib.parse.urlencode({
            'username' : self.username,
            'password' : self.password,
            'remember_me' : True
        })

        # construct the url
        login_url = self.base_url + self.login_action
        # then open it
        response = self.opener.open(login_url.encode(), login_data.encode())
        # save the cookies and return the response
        self.cj.save()
        return response


if __name__ == "__main__":

    args = sys.argv

    # check for username and password
    if len(args) != 3:
        print ("Incorrect number of arguments")
        print ("Argument pattern: username password")
        exit(1)

    username = args[1]
    password = args[2]

    # initialise and login to the website
    WebLogin('mylogin', 'mypass')

【问题讨论】:

    标签: python urllib


    【解决方案1】:

    问题是self.opener.open 期望它的第一个参数是str 类型。因此,在调用该函数时,不要在该参数上调用str.encode,只需将其作为str 类型传递即可。

    注意:出现此错误的原因是因为self.opener.open 执行isinstance 检查它是否为字符串,如果是则将它们转换为所需的数据类型。否则,它假定它已经是必需的类型(它有一个字段data)。


    编辑:上面之前将两个参数描述为需要类型为str,这是错误的。第一个参数必须是str,而第二个参数必须是Nonebytes

    【讨论】:

    • 你好,当我传递一个 str 时,我得到了这个: response = self.opener.open(login_url, login_data) File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3. 4/urllib/request.py”,第 453 行,打开 req = meth(req) 文件“/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/urllib/request.py”,第 1120 行, 在 do_request_ raise TypeError(msg) TypeError: POST data should be bytes or an iterable of bytes。它不能是 str 类型。
    • 这就像一条蛇吃自己的尾巴。 :-(
    • @ClarkKenty 很抱歉造成混乱,请参阅我的编辑以清除它。
    • 此响应 = self.opener.open(login_url, login_data.encode()) 有效!多谢!!!!!!!我现在明白了。
    • 再次抱歉。我注意到我的 response.read() 是 :看起来像 -> "b'\r\n\r\n
    猜你喜欢
    • 1970-01-01
    • 2017-12-29
    • 2020-03-11
    • 2021-09-26
    • 2019-02-02
    • 2021-11-29
    • 2020-04-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多