如何解决Python execfile运行Selenium代码时的Traceback缩进错误
问题修复说明
你遇到的IndentationError属于Python基础语法错误,Python要求函数、循环、分支等代码块内部的内容必须缩进(统一用4个空格即可),你提供的原始代码所有函数体、循环体的内容都没有做缩进处理,才触发了该报错。
需修改的核心点
- 所有
def定义的函数内部代码统一缩进4个空格 - 函数内部的
for循环代码再额外缩进一层 - 代码中的
a link属于占位内容,替换为实际站点地址时需要加英文引号包裹,拼接字符串的语法要合法 - 不要用
list作为变量名,这是Python内置关键字,会导致后续功能异常 - 若你使用的是Selenium 4.6及以上版本,无需手动指定
executable_path参数,Selenium会自动匹配本地Chrome版本下载对应驱动,直接调用即可
修复后可运行代码
from concurrent.futures.thread import ThreadPoolExecutor from selenium.webdriver.chrome.options import Options from selenium import webdriver import time import random import string chromeOptions = Options() chromeOptions.headless = True # 后台启动Chrome,不弹出可视化窗口 executor = ThreadPoolExecutor(20) # 最大同时运行线程数 def generate_random_string(length): letters = string.ascii_lowercase rand_string = ''.join(random.choice(letters) for i in range(length)) return rand_string # 提取指定页面的所有a标签链接 def getlinks(url): # 低版本Selenium请自行添加executable_path参数,值为你的chromedriver本地路径 driver = webdriver.Chrome(options=chromeOptions) link_list = [] driver.get(url) a = driver.find_elements_by_xpath('.//a') i = 0 for b in a: i = i+1 link = b.get_attribute("href") link_list.insert(i, link) driver.quit() return link_list def scrape(url): executor.submit(scraper, url) # 替换下方示例域名前缀为你的目标站点地址 executor.submit(scraper, "https://example.com/"+generate_random_string(10)) def scraper(url): driver = webdriver.Chrome(options=chromeOptions) driver.get(url) time.sleep(15) driver.quit() # 替换为你要提取链接的目标站点地址 urls = getlinks("https://example.com") for url in urls * 10: # 重复请求倍数,控制总任务量 scrape(url)
内容的提问来源于stack exchange,提问作者kiwi
相关产品推荐
相关产品推荐

