首页 > 解决方案 > urllib.request => AttributeError: 'set' 对象没有属性 'items'

问题描述

我的代码使用 urllib.request.Request 的 method = 'POST' 出现属性错误

我已经尝试了不同的语法:

POST = 'post'
method = POST

method = 'POST'

和别的...

request_login = urllib.request.Request("https://www.netflix.com/fr/Login",
    data = "userLoginId={}&password={}&rememberMe=false&flow=websiteSignUp&mode=login&action=loginAction&withFields=rememberMe%2CnextPage%2CuserLoginId%2Cpassword%2CcountryCode%2CcountryIsoCode&authURL=authURL%2FEcpWPKhtag%3D&nextPage=&showPassword=&countryCode=%2B33&countryIsoCode=FR".format(email, password),
    headers ={"""
    'Host': 'www.netflix.com',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:66.0) Gecko/20100101 Firefox/66.0',
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
    'Accept-Language': 'fr-FR',
    'Accept-Encoding': 'gzip, deflate, br',
    'Referer': 'https://www.netflix.com/fr/',
    'Content-Type': 'application/x-www-form-urlencoded',
    'Content-Length': 330,
    """},
    unverifiable = True,
    method = POST)

错误的输出是:

Traceback (most recent call last):
  File ".\checker netflix.py", line 44, in <module>
    checkPassword(email,password)
  File ".\checker netflix.py", line 23, in checkPassword
    method = POST)
  File "C:\Users\Naylor\AppData\Local\Programs\Python\Python37-32\lib\urllib\request.py", line 334, in __init__
    for key, value in headers.items():
AttributeError: 'set' object has no attribute 'items'

我希望请求成功并解析服务器响应以查看数据的参数是通过还是被拒绝

标签: pythonurllibattributeerror

解决方案


您传递的标头是一个包含字符串的集合:

headers ={"""
    'Host': 'www.netflix.com',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:66.0) Gecko/20100101 Firefox/66.0',
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
    'Accept-Language': 'fr-FR',
    'Accept-Encoding': 'gzip, deflate, br',
    'Referer': 'https://www.netflix.com/fr/',
    'Content-Type': 'application/x-www-form-urlencoded',
    'Content-Length': 330,
    """}

而不是字典:

headers = {
    'Host': 'www.netflix.com',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:66.0) Gecko/20100101 Firefox/66.0',
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
    'Accept-Language': 'fr-FR',
    'Accept-Encoding': 'gzip, deflate, br',
    'Referer': 'https://www.netflix.com/fr/',
    'Content-Type': 'application/x-www-form-urlencoded',
    'Content-Length': 330,
    }

推荐阅读