如何防止我的脚本在第一次循环后中断?

2024-04-20 03:11:27 发布

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

我用python编写了一个脚本,使用selenium从网页中获取一些特定的信息。由于网页是保密的,我不能透露网址。无论如何,我期待着我现有的刮板将点击从一个网页的20个链接中的每一个链接,并达到所需的网页,它将收集信息,并返回到以前的网页,并重复相同的,直到所有的20个链接都用尽。但是,scraper单击一个链接,转到所需的页面解析信息,但是它没有返回主页重复操作,而是中断了。我的循环过程好像有问题。下面是我的脚本中的一些行,可以给你一些想法,为我提供一个解决方法。你知道吗

for link in wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, ".section-result"))):  ##Supposed to loop through all the links
    link.click()   ##clicking each link

    name = wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, ".section-info-text")))[2] ##this is where the document i want to parse from. The browser gets here when a click is executed 
    print(name.text) #after parsing the docs the code breaks instead of getting back to main page

请注意,滚动到最右边,查看每一行所附的最低描述。谢谢。你知道吗

这就是我的错误:

line 194, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attached to the page document

Tags: ofthetoin脚本信息网页is
2条回答

问题主要在于:

  1. 您可以将所有链接作为webelement进行迭代
  2. 你开始你的循环
  3. 您单击第一个链接,它会将您带到一个新页面,导致webelement列表过时
  4. 您尝试继续使用过时的webelement,即使它们不再与任何东西连接。你知道吗

你能做的是:

伪码

linkCount = getCountOfLinks();

for x in range(0, linkCount-1):
    #Get all the links again fresh, and pick the next one each iteration
    link = getAllTheLinks[x]; 

    link.click();

    #the rest of your stuff
    name = wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, ".section-info-text")))[2]  
print(name.text)

如果代码没有返回到主页面,您可能需要执行一个将返回到上一个(主页面)的命令,例如某种类型的back按钮。我不是硒专家,但我使用过量角器(selenium的javascript包装器),也见过类似的问题。你知道吗

相关问题 更多 >