Skip to main content
 首页 » 编程设计

python之如何循环 python 命令一定次数

2024年11月24日9sky-heaven

下面的代码从网页中的表格中获取数据。

爬过一个页面后,它会转到下一页并再次做同样的事情。移动到下一页时,页面的 URL 不会改变。

我想使用一个循环,让它持续 50 或 75 次然后中断。

    driver.get(site) 
    mytable = driver.find_element_by_css_selector('.table.table...nline') 
    for row in mytable.find_elements_by_css_selector('tr'): 
        for cell in row.find_elements_by_tag_name('td'): 
            sys.stdout=open("abcd.txt","a+") 
            print(cell.text) 
            sys.stdout.close() 
     driver.find_element_by_xpath("//li[@class='button next']/a").click() 

我尝试过使用 while 循环,但在附加文件时遇到问题。

请您参考如下方法:

尝试切片:

driver.get(site) 
mytable = driver.find_element_by_css_selector('.table.table...nline') 
for row in mytable.find_elements_by_css_selector('tr')[:50]: 
    for cell in row.find_elements_by_tag_name('td'): 
        sys.stdout=open("abcd.txt","a+") 
        print(cell.text) 
        sys.stdout.close() 
driver.find_element_by_xpath("//li[@class='button next']/a").click()