本文将介绍Selenium'WebElement'对象没有属性'Get_Attribute'的详细情况,特别是关于selenium的element对象的方法的相关信息。我们将通过案例分析、数据研究等多
本文将介绍Selenium'WebElement'对象没有属性'Get_Attribute'的详细情况,特别是关于selenium的element对象的方法的相关信息。我们将通过案例分析、数据研究等多种方式,帮助您更全面地了解这个主题,同时也将涉及一些关于AttributeError'tuple'对象没有属性'get'、AttributeError: 'Member' 对象没有属性 'channel'、AttributeError: 'Pipeline' 对象没有属性 'get_feature_names、AttributeError: 'tuple' 对象没有属性 'set_author' discord.py的知识。
本文目录一览:- Selenium'WebElement'对象没有属性'Get_Attribute'(selenium的element对象的方法)
- AttributeError'tuple'对象没有属性'get'
- AttributeError: 'Member' 对象没有属性 'channel'
- AttributeError: 'Pipeline' 对象没有属性 'get_feature_names
- AttributeError: 'tuple' 对象没有属性 'set_author' discord.py
Selenium'WebElement'对象没有属性'Get_Attribute'(selenium的element对象的方法)
我将Selenium webdriver(chrome)与Python结合使用,试图从网页上的所有链接中获取 href 。当我尝试以下操作时:
items = driver.find_elements_by_tag_name("a")print itemsfor item in items: href = item.Get_Attribute(''href'') print href
它设法获取所有链接,但是在get_attribute上出现错误:
“ WebElement”对象没有属性“ Get_Attribute”
尽管到处都看起来很正常。
答案1
小编典典“ Get_Attribute”属性不存在,但是“ get_attribute”属性存在:
items = driver.find_elements_by_tag_name("a")print itemsfor item in items: href = item.get_attribute(''href'') print href
AttributeError'tuple'对象没有属性'get'
我有一个Django应用程序。但是我不能为自己已经苦苦挣扎了一段时间而犯下的错误。
Exception Value: ''tuple'' object has no attribute ''get''Exception Location: /Library/Python/2.7/site-packages/django/middleware/clickjacking.py in process_response, line 30
这就是Django提供给我的回溯。
Traceback:File "/Library/Python/2.7/site-packages/django/core/handlers/base.py" in get_response201. response = middleware_method(request, response)File "/Library/Python/2.7/site-packages/django/middleware/clickjacking.py" in process_response30. if response.get(''X-Frame-Options'', None) is not None:
我很难弄清楚为什么会发生此错误。我如何找出tuple
代码中的位置?
风景:
def products(request, category=None, gender=None, retailer_pk=None, brand_pk=None): # If the request it doesn''t have a referer use the full path of the url instead. if not request.META.get("HTTP_REFERER", None): referer = request.get_full_path() else: referer = request.META.get("HTTP_REFERER") if gender: products = ProductSlave.objects.filter(Q(productmatch__stockitem__stock__gt=0) & Q(productmatch__slave_product__master_product__gender=gender)).distinct() elif brand_pk: products = ProductSlave.objects.filter(Q(master_product__brand__pk=brand_pk)) brand = Brand.objects.get(pk=brand_pk) elif retailer_pk: retailer = Retailer.objects.get(pk=retailer_pk) products = retailer.productmatch_set.all() else: products = ProductSlave.objects.filter(Q(productmatch__stockitem__stock__gt=0)) if not retailer_pk: filt = create_filtering(productslaves=products, request=request) elif retailer_pk: filt = create_filtering(productmatches=products, request=request) sorting_selected = request.GET.get("sorter", None) # q_list is used to store all the Q''s # Then they are reduced. And then filtered if "brand" in request.GET: brand_filtering = request.GET.get("brand", None) if brand_filtering: brand_filtering = brand_filtering.split("|") q_list = [] for filter in brand_filtering: if retailer_pk: q_list.append(Q(slave_product__master_product__brand__slug=filter)) else: q_list.append(Q(master_product__brand__slug=filter)) reduced_q = reduce(operator.or_, q_list) products = products.filter(reduced_q) if "kategori" in request.GET: category_filtering = request.GET.get("kategori", None) if category_filtering: category_filtering = category_filtering.split("|") q_list = [] for filter in category_filtering: if retailer_pk: q_list.append(Q(slave_product__master_product__product_category__slug=filter)) else: q_list.append(Q(master_product__product_category__slug=filter)) reduced_q = reduce(operator.or_, q_list) products = products.filter(reduced_q) if "stoerrelse" in request.GET: size_filtering = request.GET.get("stoerrelse", None) if size_filtering: size_filtering = size_filtering.split("|") q_list = [] for filter in size_filtering: if retailer_pk: q_list.append(Q(slave_product__productmatch__stockitem__size__pk=filter)) else: q_list.append(Q(productmatch__stockitem__size__pk=filter)) reduced_q = reduce(operator.or_, q_list) products = products.filter(reduced_q) if "farve" in request.GET: color_filtering = request.GET.get("farve", None) if color_filtering: color_filtering = color_filtering.split("|") q_list = [] for filter in color_filtering: if retailer_pk: q_list.append(Q(slave_product__sorting_color__slug=filter)) else: q_list.append(Q(sorting_color__slug=filter)) reduced_q = reduce(operator.or_, q_list) products = products.filter(reduced_q) if "pris" in request.GET: price_filtering = request.GET.get("pris", None) if price_filtering: price_filtering = price_filtering.split("|") q_list = [] if retailer_pk: q_list.append(Q(price__gte=price_filtering[0])) q_list.append(Q(price__lte=price_filtering[1])) else: q_list.append(Q(productmatch__price__gte=price_filtering[0])) q_list.append(Q(productmatch__price__lte=price_filtering[1])) reduced_q = reduce(operator.and_, q_list) products = products.filter(reduced_q) if sorting_selected: if sorting_selected == filt["sorting"][0]["name"]: filt["sorting"][0]["active"] = True if retailer_pk: products = products.annotate().order_by("-price") else: products = products.annotate().order_by("-productmatch__price") elif sorting_selected == filt["sorting"][1]["name"]: if retailer_pk: products = products.annotate().order_by("price") else: products = products.annotate().order_by("productmatch__price") filt["sorting"][1]["active"] = True elif sorting_selected == filt["sorting"][2]["name"]: filt["sorting"][2]["active"] = True if retailer_pk: products = products.order_by("pk") else: products = products.order_by("pk") else: if retailer_pk: products = products.order_by("pk") else: products = products.order_by("pk") else: if retailer_pk: products = products.order_by("pk") else: products = products.order_by("pk") if brand_pk: return render(request, ''page-brand-single.html'', { ''products'': products, "sorting": filt["sorting"], "filtering": filt["filtering"], "brand": brand, }) elif retailer_pk: return (request, ''page-retailer-single.html'', { "products": products, "sorting": filt["sorting"], "filtering": filt["filtering"], "retailer": retailer, }) else: return render(request, ''page-product-list.html'', { ''products'': products, "sorting": filt["sorting"], "filtering": filt["filtering"] })
答案1
小编典典您将在这里返回元组:
elif retailer_pk: return (request, ''page-retailer-single.html'', { "products": products, "sorting": filt["sorting"], "filtering": filt["filtering"], "retailer": retailer, })
您是否忘了在render
此处添加:
elif retailer_pk: return render(request, ''page-retailer-single.html'', { "products": products, "sorting": filt["sorting"], "filtering": filt["filtering"], "retailer": retailer, })
AttributeError: 'Member' 对象没有属性 'channel'
如何解决AttributeError: ''Member'' 对象没有属性 ''channel''?
我想制作一个基于反应的不和谐机器人,代码如下:
import discord
from discord.ext import commands
import random
pershealth=50
enhealth=75
client= commands.Bot(command_prefix=''!'')
@client.event
async def on_ready():
await client.change_presence(activity=discord.Game("fighting"))
print("Works")
@client.command()
async def fight(ctx):
options=["no","yes"]
choice=random.choice(options)
if(choice=="no"):
await ctx.send("no monsters where found")
else:
msg=await ctx.send("Monster found,do you wanna fight it?")
await msg.add_reaction(emoji=u"\U0001F44D")
await msg.add_reaction(emoji=u"\U0001F44E")
@client.event
async def on_reaction_add(reaction,message):
if reaction.emoji=="?":
channel=message.channel.id
msg=await channel.send("test")
client.run("code")
但是当我运行它时,它显示错误代码 AttributeError: ''Member'' object has no attribute ''channel''。如何解决?
解决方法
on_reaction_add
的第二个参数不是 message
。它是user
。我想你想要的是
@client.event
async def on_reaction_add(reaction,user):
if reaction.emoji=="?":
channel=reaction.message.channel.id
msg=await channel.send("test")
老实说,我从未使用过 Discord 模块,对此一无所知。我只是查看了您试图从参数中获取 channel
的唯一函数的文档。然后我一直点击 reaction
中的成员链,直到很明显 reaction.message.channel
存在。我告诉你这个是因为你也可以这样做。基本上,我给了你一条鱼,并试图教你如何钓鱼。
AttributeError: 'Pipeline' 对象没有属性 'get_feature_names
如何解决AttributeError: ''Pipeline'' 对象没有属性 ''get_feature_names?
我有一个如下构建的管道:
Pipeline(steps=[(''preprocessor'',ColumnTransformer(remainder=''passthrough'',transformers=[(''text'',Pipeline(steps=[(''CV'',CountVectorizer())]),''Tweet''),(''category'',OneHotEncoder(handle_unkNown=''ignore''),[''Tweet_ID'']),(''numeric'',Pipeline(steps=[(''knnImputer'',KNNImputer(n_neighbors=2)),(''scaler'',MinMaxScale...
''CS'',''UC'',''CL'',''S'',''SS'',''UW'',...])])),(''classifier'',LogisticRegression())])
我正在尝试获取功能名称:
feature_names = lr[''preprocessor''].transformers_[0][1].get_feature_names()
coefs = lr.named_steps["classifier"].coef_.flatten()
zipped = zip(feature_names,coefs)
features_df = pd.DataFrame(zipped,columns=["feature","value"])
features_df["ABS"] = features_df["value"].apply(lambda x: abs(x))
features_df["colors"] = features_df["value"].apply(lambda x: "green" if x > 0 else "red")
features_df = features_df.sort_values("ABS",ascending=False)
features_df
但是我收到一个错误:
----> 6 feature_names = lr[''preprocessor''].transformers_[0][1].get_feature_names()
7 coefs = lr.named_steps["classifier"].coef_.flatten()
8
AttributeError: ''Pipeline'' object has no attribute ''get_feature_names
我已经看过以下答案:
- ''OneHotEncoder'' object has no attribute ''get_feature_names''
- ''Pipeline'' object has no attribute ''get_feature_names'' in scikit-learn
但不幸的是,它们并没有我预期的那么有用。
有人知道怎么解决吗? 如果需要,很乐意提供更多信息。
管道示例如下:
lr = Pipeline(steps=[(''preprocessor'',preprocessing),LogisticRegression(C=5,tol=0.01,solver=''lbfgs'',max_iter=10000))])
预处理在哪里
preprocessing = ColumnTransformer(
transformers=[
(''text'',text_preprocessing,categorical_preprocessing,c_feat),numeric_preprocessing,n_feat)
],remainder=''passthrough'')
我在拆分训练集和测试集之前将不同类型的特征分开:
text_columns=[''Tweet'']
target=[''Label'']
c_feat=[''Tweet_ID'']
num_features=[''CS'',''UW'']
按照大卫的回答和链接,我尝试如下:
对于数字:
class NumericalTransformer(BaseEstimator,TransformerMixin):
def __init__(self):
super().__init__()
def fit(self,X,y=None):
return self
def transform(self,y=None):
# Numerical features to pass down the numerical pipeline
X = X[[num_features]]
X = X.replace([np.inf,-np.inf],np.nan)
return X.values
# Defining the steps in the numerical pipeline
numerical_pipeline = Pipeline(steps=[
(''num_transformer'',NumericalTransformer()),(''imputer'',(''minmax'',MinMaxScaler())])
对于分类:
class CategoricalTransformer(BaseEstimator,TransformerMixin):
def __init__(self):
super().__init__()
# Return self nothing else to do here
def fit(self,y=None):
return self
# Helper function that converts values to Binary depending on input
def create_binary(self,obj):
if obj == 0:
return ''No''
else:
return ''Yes''
# Transformer method for this transformer
def transform(self,y=None):
# Categorical features to pass down the categorical pipeline
return X[[c_feat]].values
# Defining the steps in the categorical pipeline
categorical_pipeline = Pipeline(steps=[
(''cat_transformer'',CategoricalTransformer()),(''one_hot_encoder'',OneHotEncoder(handle_unkNown=''ignore''))])
和文本功能:
class TextTransformer(BaseEstimator,y=None):
# Text features to pass down the text pipeline
return X[[''Tweet'']].values
# Defining the steps in the text pipeline
text_pipeline = Pipeline(steps=[
(''text_transformer'',TextTransformer()),(''cv'',CountVectorizer())])
然后我将数字、文本和分类管道水平组合成一个完整的大管道:
# using FeatureUnion
union_pipeline = FeatureUnion(transformer_list=[
(''categorical_pipeline'',categorical_pipeline),(''numerical_pipeline'',numerical_pipeline),(''text_pipeline'',text_pipeline)])
最后:
# Combining the custom imputer with the categorical,text and numerical pipeline
preprocess_pipeline = Pipeline(steps=[(''custom_imputer'',CustomImputer()),(''full_pipeline'',union_pipeline)])
目前还不清楚的是如何获取特征名称。
解决方法
您需要实现专用的 get_feature_names
函数,因为您使用的是自定义转换器。
有关详细信息,请参阅 this question,您可以在其中找到代码示例。
AttributeError: 'tuple' 对象没有属性 'set_author' discord.py
如何解决AttributeError: ''tuple'' 对象没有属性 ''set_author'' discord.py?
再次,我一直在考虑我的准备问题。我刚刚开始为不和谐编写机器人并坐了几个小时寻找错误,最终我还是没有找到它。这就是我写论坛帖子作为最后手段的原因。我期待您的帮助,并在此先感谢您。
这是我的代码:
@tasks.loop(hours=24)
async def covid_hour():
channel = client.get_channel(809881992367702117),embed = discord.Embed(
title = "Dane dot. COVID-19 w Polsce:",color = discord.Color.blue(),),url = ''API''
async with aiohttp.ClientSession() as session:
raw_response = await session.get(url)
response = await raw_response.text()
response = json.loads(response)
embed.set_author(name=str(f''{date}''))
embed.add_field(name=''• **Kraj**:'',value=str(f"Polska"),inline=False)
embed.add_field(name=''• **Nowe zakażenia**:'',value=str(f"{response[''dailyInfected'']}"),inline=True)
embed.add_field(name=''• **Nowe zgony**:'',value=str(f"{response[''dailyDeceased'']}"),inline=True)
embed.add_field(name=''• **Nowe testy**:'',value=str(f"{respons[''dailyTested'']}"),inline=True)
embed.add_field(name=''• **Nowe uzdrowienia**:'',value=str(f"{response[''dailyRecovered'']}"),inline=True)
embed.add_field(name=''• **Aktualnie zakażonych**:'',value=str(f"{respons[''activeCase'']}"),inline=True)
embed.add_field(name=''• **Łącznie potwierdzonych**:'',value=str(f"{response[''infected'']}"),inline=True)
embed.add_field(name=''• **Łączne zgony**:'',value=str(f"{response[''deceased'']}"),inline=True)
embed.add_field(name=''• **Wyzdrowiałych**:'',value=str(f"{response[''recovered'']}"),inline=True)
embed.add_field(name=''• **Nowych na kwarantannie**:'',value=str(f"{response[''dailyQuarantine'']}"),inline=True)
embed.set_footer(text="dBot created by Diablo#4700")
await channel.send(embed=embed)
#await channel.send(''`` ``'')
控制台错误:
Unhandled exception in internal background task ''covid_hour''.
Traceback (most recent call last):
File "C:\Users\konta\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\python38\site-packages\discord\ext\tasks\__init__.py",line 101,in _loop
await self.coro(*args,**kwargs)
File "bot.py",line 64,in covid_hour
embed.set_author(name=str2(f''{date}''))
AttributeError: ''tuple'' object has no attribute ''set_author''
解决方法
在您创建 discord.Embed 实例的那一行,最后有一个 ,
。这告诉python它是一个tuple
。因此,将其删除将解决此问题。
关于Selenium'WebElement'对象没有属性'Get_Attribute'和selenium的element对象的方法的问题我们已经讲解完毕,感谢您的阅读,如果还想了解更多关于AttributeError'tuple'对象没有属性'get'、AttributeError: 'Member' 对象没有属性 'channel'、AttributeError: 'Pipeline' 对象没有属性 'get_feature_names、AttributeError: 'tuple' 对象没有属性 'set_author' discord.py等相关内容,可以在本站寻找。
本文标签: