python - 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)
解决方案
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.
推荐阅读
- python - 需要帮助理解“未定义 matplotlib”错误
- python - 将工作目录更改为 AWS 上的 S3 存储桶
- android - 使用物理鼠标单击时,可绘制选择器失去悬停状态
- javascript - 如何将 webpack 文件加载器与 three.js 一起使用?
- mysql - 错误 1064 mysql 错误
- python - 如何从另一个类中的一个类访问 id
- javascript - p5.js 如何让一条线在两个方向上无穷无尽
- amazon-web-services - 使用 AWS Athena 查询 S3 对象标记
- sql - SQL SELECT 中的布尔逻辑
- javascript - 如何从 textarea 获取 html、css、js 代码并编译