I want to write a code in Python that attaches a table on the web copied to the clipboard to an Excel file.

Asked 2 years ago, Updated 2 years ago, 119 views

The target website has a key, so I can't use scraping, so I'd like to copy it to the clipboard and then paste it into Excel.

I would like to copy to clipboard → read as data frame → CSV conversion → paste into Excel, but when I tried to use pandas.read_clipboard() at the first stage, the following error occurred and it didn't work.

error message

Piperclip could not find a copy/paste mechanism for your system

I would like to know if there is anyone who knows the cause or who knows other ways to do it.
The code is written in Google colab.

python pandas openpyxl

2022-09-30 21:46

1 Answers

If the machine that opens the excel file is the same as the web browsing machine, you can simply open the excel file and paste it.
It's the same with other spreadsheets like Google spreadsheets.

The clipboard is managed by the GUI system and must be a GUI program or linked to the GUI library to read the clipboard directly.
Pandas is neither of them, so some outside assistance is needed (hereafter, the features used in the read_clipboard per platform)

  • If it's a Windows environment, you don't need additional modules, but it looks like you're using windll/"msvcrt"
  • Mac environments use the pyobjc modules, so they must be included in macOS
  • Linux distributions require a xclip or xsel package.Or PyQt5 module required

For example, xclip should link the libx11-dev library, and you can do the following

$echo-e "hello\nworld\n" | xclip-selection clipboard#copy
$ xclip-selection clipboard-o# paste
hello
world

Pandas is running read_clipboard() by calling them internally. Reference (Source): https://github.com/pandas-dev/pandas/blob/master/pandas/io/clipboard/_init_.py

In Google colab, Ubuntu appears to be used in the operating system

!cat/etc/os-release# When running in the cell:

NAME="Ubuntu"
VERSION="18.04.5 LTS (Bionic Beaver)"
ID = ubuntu
ID_LIKE=debian
PRETTY_NAME = "Ubuntu 18.04.5 LTS"
VERSION_ID="18.04"
HOME_URL="https://www.ubuntu.com/"
SUPPORT_URL="https://help.ubuntu.com/"
BUG_REPORT_URL="https://bugs.launchpad.net/ubuntu/"
PRIVACY_POLICY_URL="https://www.ubuntu.com/legal/terms-and-policies/privacy-policy"
VERSION_CODENAME=bionic

If you call pandas.read_clipboard() in pandas, you will try to use the various tools in the past to get the clipboard for that environment... you will fail.
However, there is no point in reading the clipboard on the server side, so if you want it to work, you have to create a Jupiter environment locally


2022-09-30 21:46

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.