【问题标题】:Selenium/Python2.7 Check if elements in list matches one on the web pageSelenium/Python2.7 检查列表中的元素是否与网页上的元素匹配
【发布时间】:2015-12-24 10:23:59
【问题描述】:
from selenium import webdriver

fp = webdriver.FirefoxProfile('')
driver = webdriver.Firefox(firefox_profile=fp)
driver.set_window_size(1400, 1000)
driver.get('')

list_of_elements = driver.find_elements_by_css_selector('img[title][src*=images]')

srcs = [ele.get_attribute("src") for ele in list_of_elements]
print srcs

我上面的代码打印出网页上图片的 src 链接。链接看起来都像http://example.com/test.gif,现在我有一个图像的“测试”部分列表,如果它们出现,我想点击它们。所以我需要检查“srcs”列表,当它与“测试”匹配时,它会单击该图像。感谢任何帮助!

【问题讨论】:

  • 您尝试了哪些方法,结果如何?就像你在学校做的那样……请展示你的作品。 :) 这是在 SO 上回答问题的过程的一部分。它对您很有帮助,因为它迫使您调查自己的问题并仔细考虑。它还向读者证明你做了功课,并做出了合理的尝试来回答你自己的问题。第三,它可以帮助读者发现和诊断问题,从而为您提供更好的答案,减少我们浪费的时间。

标签: python selenium element src


【解决方案1】:

这个想法是事先准备一个所需文件名的set,从每个匹配图像的src属性中提取文件名,并检查文件名是否在集合中:

import re 

filenames = {"test1", "test2", "test3"}  # this is a set

pattern = re.compile(r"/(\w+)\.gif$")

result = []
for ele in list_of_elements:
    src = ele.get_attribute("src")
    match = pattern.search(src)
    if match:
        filename = match.group(1)
        if filename in filenames:  # since "filenames" is  a set, lookups are O(1)
            result.append(filename)

print(result)

【讨论】:

    猜你喜欢
    • 2018-04-15
    • 1970-01-01
    • 1970-01-01
    • 2022-01-24
    • 1970-01-01
    • 2015-10-03
    • 2020-05-18
    • 1970-01-01
    • 2011-04-14
    相关资源
    最近更新 更多