Python “TypeError: 'builtin_function_or_method' object is not subscriptable"

Python “TypeError: 'builtin_function_or_method' object is not subscriptable"

谢谢!! 1. 里面好像有什么错误,但是我没找到。 2、原来也是这样,不过现在后面跟着一个代码块:

from urllib.request import Request, urlopen
from urllib.error import URLError,HTTPError
from bs4 import BeautifulSoup
import re

print('https://v.qq.com/x/page/h03425k44l2.html\\n\\https://v.qq.com/x/cover/dn7fdvf2q62wfka/m0345brcwdk.html\\n\\http://v.qq.com/cover/2/2iqrhqekbtgwp1s.html?vid=c01350046ds')
web = input('请输入网址:')
if re.search(r'vid=',web) :
    patten =re.compile(r'vid=(.*)')
    vid=patten.findall(web)
    vid=vid[0]

else:
    newurl = (web.split("/")[-1])
    vid =newurl.replace('.html', ' ')
#从视频页面找出vid

getinfo='http://vv.video.qq.com/getinfo?vids{vid}&otype=xlm&defaultfmt=fhd'.format(vid=vid.strip())
def getpage(url):
    req = Request(url)
    user_agent = 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit'
    req.add_header('User-Agent', user_agent)
    try:
        response = urlopen(url)
    except HTTPError as e:
        print('The server couldn\\'t fulfill the request.')
        print('Error code:', e.code)
    except URLError as e:
        print('We failed to reach a server.')
        print('Reason:', e.reason)
    html = response.read().decode('utf-8')
    return(html)
#打开网页的函数  

a = getpage(getinfo)

soup = BeautifulSoup(a, "html.parser")
for e1 in soup.find_all('url'):
    ippattent = re.compile(r"((?:(2[0-4]\\d)|(25[0-5])|([01]\\d\\d?))\\.){3}(?:(2[0-4]\\d)|(255[0-5])|([01]?\\d\\d?))")
    if re.search(ippattent,e1.get_text()):
        ip=(e1.get_text())
for e2 in soup.find_all('id'):
    idpattent = re.compile(r"\\d{5}")
    if re.search(idpattent,e2.get_text()):
        id=(e2.get_text())
filename=vid.strip()+'.p'+id[2:]+'.1.mp4'
#找到ID和拼接FILENAME

getkey='http://vv.video.qq.com/getkey?format={id}&otype=xml&vt=150&vid{vid}&ran=0%2E9477521511726081\\&charge=0&filename={filename}&platform=11'.format(id=id,vid=vid.strip(),filename=filename)
#利用getinfo中的信息拼接getkey网址
b = getpage(getkey)

key=(re.findall(r'<key>(.*)<\\/key>',b))

videourl=ip+filename+'?'+'vkey='+key[0]

print('视频播放地址 '+videourl)
#完成了

我运行它并得到这个:

Traceback (most recent call last):
  File "C:\Users\DYZ_TOGA\Desktop\qq.py", line 46, in <module>
    filename=vid.strip()+'.p'+id[2:]+'.1.mp4'
TypeError: 'builtin_function_or_method' object is not subscriptable

我该怎么办?我不知道如何更改我的代码来纠正 it.Thank 你 :)

id 是 python 中的内置函数。看来您正在使用相同的存储变量。使用关键字作为变量名是坏习惯。请改用其他名称。

问题的根源在这里:

if re.search(idpattent,e2.get_text()):
    id=(e2.get_text())

如果这是假的,你永远不会设置 id。这意味着 id 是该名称的 built-in 函数,它获取任何对象的唯一 ID。由于它是一个函数,而不是你期望的字符串,你不能这样做:

id[2:]

因此出现错误。

我的建议是:

  1. 使用不同的变量名;在这种情况下你会得到一个关于它没有被定义的错误,这会让问题更容易解决

  2. 当找不到ID时,不要继续脚本;无论如何都行不通。如果您希望找到它,但不确定为什么没有找到,那您应该单独提出一个不同的问题。

if re.search(idpattent,e2.get_text()):
        id=(e2.get_text())
filename=vid.strip()+'.p'+id[2:]+'.1.mp4'

如果上述"if"不成立,id将不会被设置为字符串值。

默认情况下 id 是一个函数 python 。所以你不能做 id[2:]

因为 python 需要 id()。