我正在尝试设置脚本以每天从网站中提取数据,但我无法让 Python 实际读取表格 - 我不是专业编码人员。我尝试了两种方法:
1) 使用 Beautiful Soup 抓取表格(标题、行等)
2) 使用网站的excel导出按钮
具体网址如下: https://scgenvoy.sempra.com/index.html#nav=/Public/ViewExternalLowOFO.getLowOFO%3Frand%3D200
到目前为止我的代码是:
#Imports
import requests
import urllib.request
import pandas as pd
from lxml import html
import lxml.html as lh
from bs4 import BeautifulSoup
`URL ='https://scgenvoy.sempra.com/index.html#nav=/Public/ViewExternalLowOFO.getLowOFO%3Frand%3D200'`
#Create a handle, page, to handle the contents of the website
requests.packages.urllib3.disable_warnings()
page = requests.get(URL, verify=False)
我认为最简单的方法是使用
触发“导出”功能xpath //*[@id="content"]/form/div[2]/div/table/tbody/tr/td[4]/table/tbody/tr/td[1]/a
非常感谢所有帮助!
最佳答案
你的 website正在使用导出按钮附加动态表数据。所以基本上你需要使用 Selenium
包来处理动态数据。根据您的浏览器下载 selenium 网络驱动程序。
对于 chrome 浏览器:
http://chromedriver.chromium.org/downloads
为 chrome 浏览器安装网络驱动程序:
unzip ~/Downloads/chromedriver_linux64.zip -d ~/Downloads
chmod +x ~/Downloads/chromedriver
sudo mv -f ~/Downloads/chromedriver /usr/local/share/chromedriver
sudo ln -s /usr/local/share/chromedriver /usr/local/bin/chromedriver
sudo ln -s /usr/local/share/chromedriver /usr/bin/chromedriver
selenium 教程
https://selenium-python.readthedocs.io/
导出Excel文件:
from selenium import webdriver
import time
driver = webdriver.Chrome('/usr/bin/chromedriver')
driver.get('https://scgenvoy.sempra.com/index.html#nav=/Public/ViewExternalLowOFO.getLowOFO%3Frand%3D200')
time.sleep(3)
excel_button = driver.find_element_by_xpath("//div[@id='content']/form/div[2]/div/table/tbody/tr/td[4]/table/tbody/tr/td[2]/a")
print(excel_button.click())
其中 "/usr/bin/chromedriver"
chrome 网络驱动程序路径。
关于javascript - 如何使用 Python 触发从网站下载文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56369067/