首页 > 解决方案 > Python(Selenium)脚本覆盖文件

问题描述

使用以下在提取方面“工作”的代码,输出将覆盖主 html 输出“文件”中的每个新页面。我对此很陌生,并且确信这是一个愚蠢的编码错误,但我只是没有看到它。

换句话说,它正在浏览页面并提取信息,但每次完成页面时,它都会覆盖 html 中已有的内容,因此在任何给定时间我只有 p。2 或 p。16等。我需要它来继续添加到页面或为每个页面创建一个html文件(我认为后者是首选?)。

非常感激任何的帮助。

这只是一个较大脚本的一部分,但我试图在运行整个脚本之前确保每个部分都能正常工作。

谢谢你的时间!

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
from time import sleep
import os

allpages=[]
for i in range(2,1575): *** the main page is a different url so starting on p. 2
    allpages.append("url here"+str(i))

completedlist=[]

for eachpage in allpages[0:2]: *** just testing; will change to :1575
#options = Options()
options.headless = True
driver = webdriver.Chrome(options=options, executable_path='mypath')
driver.get(eachpage)
print ('Headless Chrome Initialized: '+eachpage)

with open("./capture/filenamehere"+str(i)+".html", "w") as f:
    f.write(driver.page_source)

completedlist.append(eachpage)

标签: pythonselenium

解决方案


You are opening file in writing mode therefore your output get overwrite every time. Change 'w' in open with 'a' which means append mode, now your file will not be get overwrite the new content will be appended on the end.


推荐阅读