繁体   English   中英

在Python中使用Selenium在Firefox上保存网页

[英]Using Selenium in Python to save a webpage on Firefox

我试图在Python使用Selenium来保存MacOS Firefox上的网页。

到目前为止,我已经设法点击COMMAND + S弹出SAVE AS window 然而,

我不知道如何:

  1. 更改文件的目录,
  2. 更改文件的名称,和
  3. 单击SAVE AS按钮。

有人可以帮忙吗?

下面是我用来点击COMMAND + S的代码:

ActionChains(browser).key_down(Keys.COMMAND).send_keys("s").key_up(Keys.COMMAND).perform()

此外,我使用这种方法的原因是我遇到Unicode编码错误 : -

  1. 将page_source写入html文件和
  2. 将报废信息存储到csv文件中。

写一个html文件:

file_object = open(completeName, "w")
html = browser.page_source
file_object.write(html)
file_object.close() 

写入csv文件:

csv_file_write.writerow(to_write)

错误:

UnicodeEncodeError:'ascii'编解码器不能对位置1中的字符u'\\ xf8'进行编码:序数不在范围内(128)

你想要实现的是Selenium无法做到的。 打开的对话框不是Selenium可以与之交互的对象。

您可以执行的page_source操作是收集page_source ,它将为您提供单个页面的完整HTML并将其保存到文件中。

import codecs

completeName = os.path.join(save_path, file_name)
file_object = codecs.open(completeName, "w", "utf-8")
html = browser.page_source
file_object.write(html)

如果你真的需要保存整个网站,你应该使用像AutoIT这样的工具。 这样就可以与保存对话框进行交互。

with open('page.html', 'w') as f:
    f.write(driver.page_source)

您无法与保存文件对话框等系统对话框进行交互。 如果你想保存页面html,你可以这样做:

page = driver.page_source
file_ = open('page.html', 'w')
file_.write(page)
file_.close()

这是RemcoW提供的答案的完整,有效的例子:

首先必须安装webdriver,例如pip install selenium chromedriver_installer

#!/usr/bin/env python
# -*- coding: utf-8 -*-

# core modules
import codecs
import os

# 3rd party modules
from selenium import webdriver


def get_browser():
    """Get the browser (a "driver")."""
    # find the path with 'which chromedriver'
    path_to_chromedriver = ('/usr/local/bin/chromedriver')
    browser = webdriver.Chrome(executable_path=path_to_chromedriver)
    return browser


save_path = os.path.expanduser('~')
file_name = 'index.html'
browser = get_browser()

url = "https://martin-thoma.com/"
browser.get(url)

complete_name = os.path.join(save_path, file_name)
file_object = codecs.open(complete_name, "w", "utf-8")
html = browser.page_source
file_object.write(html)
browser.close()

您可以使用pyautogui库实现此目的,但如果您必须在循环中保存多个页面,则无法在屏幕上执行任何其他任务。

import pyautogui
import time 
pyautogui.hotkey('ctrl', 's')
time.sleep(1)   
pyautogui.typewrite("file name")
time.sleep(1)
pyautogui.hotkey('enter')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM