Python 保持';类型错误:';非类型';对象不可调用';配上漂亮的汤和蟒蛇

Python 保持';类型错误:';非类型';对象不可调用';配上漂亮的汤和蟒蛇,python,beautifulsoup,typeerror,nonetype,Python,Beautifulsoup,Typeerror,Nonetype,我是一名初学者,正在努力学习一门课程,所以这个问题可能非常简单,但我正在运行这个(无可否认是混乱的)代码(保存在文件x.py下),以从具有以下行格式的网站中提取链接和名称: 所以我设置了这个: 导入urllib.request、urllib.parse、urllib.error 从bs4导入BeautifulSoup 导入ssl #忽略SSL证书错误 ctx=ssl.create\u default\u context() ctx.check_hostname=False ctx.veri

我是一名初学者,正在努力学习一门课程,所以这个问题可能非常简单,但我正在运行这个(无可否认是混乱的)代码(保存在文件x.py下),以从具有以下行格式的网站中提取链接和名称:

  • 所以我设置了这个: 导入urllib.request、urllib.parse、urllib.error 从bs4导入BeautifulSoup 导入ssl #忽略SSL证书错误 ctx=ssl.create\u default\u context() ctx.check_hostname=False ctx.verify_mode=ssl.CERT_NONE

    url = input('Enter - ')
    html = urllib.request.urlopen(url, context=ctx).read()
    soup = BeautifulSoup(html, 'html.parser')
    for line in soup:
        if not line.startswith('<li'):
            continue
        stuff = line.split('"')
        link = stuff[3]
        thing = stuff[4].split('<')
        name = thing[0].split('>')
        count = count + 1
        if count == 18:
            break
    print(name[1])
    print(link)
    
    url=input('Enter-'))
    html=urllib.request.urlopen(url,context=ctx.read())
    soup=BeautifulSoup(html,'html.parser')
    对于汤中的线:
    
    如果不是line.startswith('
    line
    不是字符串,它没有
    startswith()
    方法。它是,因为BeautifulSoup已将HTML源文本解析为富对象模型。不要尝试将其视为文本

    导致此错误的原因是,如果您访问它不知道的
    标记
    对象上的任何属性,它会执行一个(因此在这里它执行
    line.find('startswith')
    ),并且由于没有具有该名称的元素,因此返回
    None
    None.startswith()
    ,然后失败,出现您看到的错误

    如果要查找第18个
  • 元素,只需向BeautifulSoup查询该特定元素:

    soup = BeautifulSoup(html, 'html.parser')
    li_link_elements = soup.select('li a[href]', limit=18)
    if len(li_link_elements) == 18:
        last = li_link_elements[-1]
        print(last.get_text())
        print(last['href'])
    

    这将使用查找只查找
    ,其中将包含来自任何嵌套元素(例如
    或其他额外标记)的文本,并且
    href
    属性为。

    我不确定您为什么要使用代码在BeautifulSoup元素上拆分文本。请这样做,您会发现提供的API与您在此处使用的API非常不同。如果您要使用
    startswith
    ,请先转换为字符串。
    soup = BeautifulSoup(html, 'html.parser')
    li_link_elements = soup.select('li a[href]', limit=18)
    if len(li_link_elements) == 18:
        last = li_link_elements[-1]
        print(last.get_text())
        print(last['href'])