python - “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))
我该如何克服这个错误?
解决方案
好吧,您的 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
是一个整数。这就是你得到错误的原因。
推荐阅读
- c# - IIS 托管的 WCF Web 服务配置文件
- android - 从 Gradle 中的依赖项中排除项目
- php - 在 Woocommerce 中显示税率为 0% 时的税线
- jquery - Uncaught SyntaxError: Unexpected token %
- c# - 从 Session.GetObjects 获取列表
- asp.net - 使用 AJAX Asp.Net MVC 更改页面问题
- javascript - Vue.js 使用 document.getElementById('id').value 设置输入值不起作用
- java - JTable - CellHighlight 和 RowHighlight 问题
- java - 一个请求中带有 json 的 REST API 多部分文件
- java - 没有时区的 Java 字符串到日期