如何用Selenium、Python点击类的类?(正在爬网microsoft网站)

2024-09-29 19:12:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我想爬网微软网站删除我的照片。在

我想点击所有照片(最多100张),然后点击删除按钮,重复4-5次。在

“ItemCheck”类是选择照片的按钮。在

但是还有另一个与具体照片无关的“ItemCheck”类。在

两个“ItemCheck”类的区别是祖先。在

所以我想先找到“List cell”类,然后在“List cell”类中找到“ItemCheck”类。在

我如何解决这个问题? 我用了Python和升华。在

我试着用“find_elements_by_css_selector”作为代码,但是“row”是空的!=>;[]

from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from selenium import webdriver
from selenium.webdriver.common.by import By

EMAILFIELD = (By.ID, "i0116")
PASSWORDFIELD = (By.ID, "i0118")
NEXTBUTTON = (By.ID, "idSIButton9")

browser = webdriver.Firefox(executable_path="mypath/firefoxdriver_win64/geckodriver.exe")
browser.get('https://login.live.com')

WebDriverWait(browser, 10).until(EC.element_to_be_clickable(EMAILFIELD)).send_keys("mymail")
WebDriverWait(browser, 10).until(EC.element_to_be_clickable(NEXTBUTTON)).click()

WebDriverWait(browser, 10).until(EC.element_to_be_clickable(PASSWORDFIELD)).send_keys("mypassword")
WebDriverWait(browser, 10).until(EC.element_to_be_clickable(NEXTBUTTON)).click()

browser.get('https://onedrive.live.com/?v=photos')
browser.implicitly_wait(5)

#Click class="ItemTile-rowCheck" which the ancestor is class="List-cell"
elements = browser.find_elements_by_xpath('//div[@class="List-cell"]') #bring div elements which have class="List-cell"
print(elements)
for i in range(0,24) : #temporory
    print(i)

    row = elements[i].find_elements_by_css_selector('.ItemTile-rowCheck') #find .ItemTile-rowCheck among elements[i]
    print(row)
    print(row.click)

当代码运行结束时,结果是这样。在

^{pr2}$

Tags: fromimportbrowserbyseleniumcellelementsfind
2条回答

如下图所示更改回路

elements = browser.find_elements_by_xpath("//div[@class='List-cell']//*[@class='ItemTile-rowCheck']")
print('Total rows ' + str(len(elements)))
for i in range(1,len(elements)) : # iterates through all elements
    print(i)
    row = browser.find_elements_by_xpath("//div[@class='List-cell']//*[@class='ItemTile-rowCheck']")[i]
    print(row)
    print(row.click)

@supputuri

多亏了你,我学会了如何使用xpath!非常感谢你! 顺便说一句,我也用这种方式选择了一个日期覆盖了整张照片。 但这样只选择了偶数数组,[0],[2],[4]。。 如果范围从1开始,则选择奇数数组,[1],[3],[5]。。在

#Before
elements = browser.find_elements_by_xpath("//span[@class='od-AllPhotosHeader-check can-select']")
print('Total rows ' + str(len(elements)))
for i in range(0,len(elements)) :
    print(i)
    row = browser.find_elements_by_xpath("//span[@class='od-AllPhotosHeader-check can-select']")[i]
    row.click()

所以我就这样改了代码, 而且这个成功了! 我想知道什么是不能选择整数与第一个代码?在

^{pr2}$

我很抱歉这样回复,但评论太有限,无法添加代码。在

相关问题 更多 >

    热门问题