错误登录脚本对象没有属性' __ getitem __'

时间:2015-04-02 03:37:37

标签: python beautifulsoup

你好我创建一个登录脚本,我有一个错误

我的代码

 # -*- coding: UTF-8 -*-
    from bs4 import BeautifulSoup
    import requests
    import sys
    import os

    #givenURL = sys.argv[1]


    headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}

    # initialize session
    session = requests.Session()
    response = session.get("http://website.fr/", headers=headers)
    soup = BeautifulSoup(response.content)
    token = soup.find('a', {'name':'return'})['value']
    token2 = soup.find('a', {'type':'hidden'})['name']
    print token token2

错误是

File "logins", line 17, in <module>
    token = soup.find('a', {'name':'return'})['value']
TypeError: 'NoneType' object has no attribute '__getitem__'

信息令牌登录

<input type="hidden" name="return" value="sommetoken=" />
    <input type="hidden" name="sommetoken" value="1" /></form>

1 个答案:

答案 0 :(得分:0)

bs4.BeautifulSoup.find在找不到它要找的内容时返回Nonehttp://www.crummy.com/software/BeautifulSoup/bs4/doc/#find

您的soup.find('a', {'name': 'return'})会与a标记与name属性return匹配。

要匹配并解压缩上述HTML,您可以使用soup.find('input', {'name': 'return'})['value']

In [26]: html = """
....: <input type="hidden" name="return" value="sommetoken=" />
....:     <input type="hidden" name="sommetoken" value="1" />"""
In [27]: soup = bs4.BeautifulSoup(html)
In [29]: soup.find("input", {"name": "return"})
Out[29]: <input name="return" type="hidden" value="sommetoken="/>
In [30]: soup.find("input", {"name": "return"})["value"]
Out[30]: u'sommetoken='