【问题标题】:Check if List Contains Specific String, Problem [closed]检查列表是否包含特定字符串,问题[关闭]
【发布时间】:2019-01-04 15:13:30
【问题描述】:

在使用我的 Selenium Python 程序时,我试图跳过列入黑名单的项目,但我不知道如何使这个 sn-p 工作 -

    channel = driver.find_element_by_xpath('/html/body/ytd-app/div[1]/ytd-page-manager/ytd-watch-flexy/div[3]/div[1]/div/div[7]/div[3]/ytd-video-secondary-info-renderer/div/div[2]/ytd-video-owner-renderer/a').get_attribute('aria-label')

    print(channel)   
    print(blacklistchannels[3])

    if channel in blacklistchannels:
        print('Blacklisted Channel, Skipping...')
        continue
    else:
        print('There is still a problem')

即使在打印时,频道名称和列入黑名单的项目 (3) 完全相同。它仍然跟随 else,并打印出“仍然存在问题”

任何帮助将不胜感激,谢谢!

编辑 - 那里的 continue 与 sn-p 无关,它只是为了继续一个循环。

解决方案 - .Stripping() 黑名单和频道名称,以消除我为换行符所使用的空格和 /n。

【问题讨论】:

  • 显然不完全相同,但我们看不到任何数据。请同时显示channelblacklistedchannel
  • 用相关的 HTML 更新问题
  • 它们不一样 - 可能是空格或其他。发送minimal reproducible example 以获得帮助 - 这段代码太模糊了。
  • 猜测 中,channel 在某个容器中,例如一个列表
  • 我会看看这个stackoverflow.com/questions/14312869/…,还有,你为什么用'继续'?

标签: python selenium


【解决方案1】:

很难猜出else() 块被执行的原因。也许相关的 HTML 会帮助我们诊断问题。

但我怀疑 get_attribute('aria-label') 提取的 value 包含 空格 / 空格

解决方案

你可以使用pythonstrip()方法来去除空格/空格,如下:

channel = driver.find_element_by_xpath('/html/body/ytd-app/div[1]/ytd-page-manager/ytd-watch-flexy/div[3]/div[1]/div/div[7]/div[3]/ytd-video-secondary-info-renderer/div/div[2]/ytd-video-owner-renderer/a').get_attribute('aria-label').strip(' \n')
print(channel)   
print(blacklistchannels[3])
if channel in blacklistchannels:
    print('Blacklisted Channel, Skipping...')
else:
    print('There is still a problem')

【讨论】:

  • 我刚刚注意到第二个打印件(列表中的那个)下面有一个空行。这让我意识到这可能是我打印到文本文件中以创建新行的 /n。我将如何剥离 /n 的整个列表?
  • 查看更新的答案并让我知道状态。
  • blacklistchannels = [x.strip('\n') for x in blacklistchannels] 但在将数据放入列表时,删除换行符可能更容易。
  • 您可以使用print(repr(blacklistchannels[3])) 来查看没有格式化的内容。
  • @DebanjanB 谢谢,我自己想出来的。 aria-label 中没有任何空格,问题实际上是为我的文本文件中的新行插入了 /n。只是 for 循环列表并将它们剥离到另一个列表中,现在效果很好。
【解决方案2】:

为什么不直接使用这个?

channel = driver.find_element_by_xpath('/html/body/ytd-app/div[1]/ytd-page-manager/ytd-watch-flexy/div[3]/div[1]/div/div[7]/div[3]/ytd-video-secondary-info-renderer/div/div[2]/ytd-video-owner-renderer/a').get_attribute('aria-label')

print(channel)   
print(blacklistchannels[3])

if channel in blacklistchannels:
    print('Blacklisted Channel, Skipping...')
    # continue
else:
    print('There is still a problem')

我不确定你为什么在 if 语句中使用 continue

【讨论】:

  • 检查我所做的编辑...
【解决方案3】:

关于如何捕捉此类问题的旁注:

>>> a = "hello\r\n"
>>> print(a)
hello

>>> 

如您所知,使用普通打印语句很容易忽略“\r\n”。

这就是repr() 有帮助的地方:

>>> a = "hello\r\n"
>>> print(repr(a))
'hello\r\n'
>>> 

【讨论】:

    猜你喜欢
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-23
    • 2020-04-17
    • 1970-01-01
    相关资源
    最近更新 更多