首页 > 解决方案 > “int”没有属性“get”

问题描述

我应该输入列出众多名称的网站的网址。然后“在第 18 位找到链接(名字是 1)。点击该链接。重复此过程 7 次。答案是您检索的姓氏。提示:您最后一页的名称的第一个字符将加载是:C" 我总是收到一个错误,即'int object has no attribute get'。到目前为止,这是我的代码: import urllib.request, urllib.parse, urllib.error from bs4 import BeautifulSoup import ssl

# Ignore SSL certificate errors
ctx = ssl.create_default_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')


# Retrieve all of the anchor tags
tags = soup('a')
try:
    input("please enter a number between 0 and 129: ")
except:
    print("Invalid input")
x=list(range(0,129))
for tag in range(len(x)):
    print(tag.get('href', None))

我该如何克服这个错误?

标签: pythonurlbeautifulsoup

解决方案


好吧,您的 range/len/list/range 循环完全是胡说八道。您显然需要遍历收到的标签,甚至没有存储您读取的数字。

# Retrieve all of the anchor tags
tags = soup('a')
try:
    tagno = int(input("please enter a number between 0 and 129: "))
except:
    print("Invalid input")
for n,tag in enumerate(tags):
    if n+1 == tagno:
        print(tag.get('href', None))
        break

作为对您遇到错误的原因的解释,让我们看一下您的代码:

x=list(range(0,129))

这意味着 x 是 [0,1,2,3,4,...,127,128],长度为 129。接下来:

for tag in range(len(x)):

这将产生与您存储的序列完全相同的序列x。所以,tag将是 0,然后是 1,然后是 2,等等。

    print(tag.get('href',None))

所以这里,tag是一个整数。这就是你得到错误的原因。


推荐阅读