使用Selenium从python中单击“下载CSV”[复制]

ggazkfy8  于 2023-04-27  发布在  Python
关注(0)|答案(2)|浏览(125)

此问题已在此处有答案

python selenium click on button(9个回答)
15天前关闭。
此帖子于15天前编辑并提交审核,未能重新打开帖子:
原始关闭原因未解决
网站为https://www.punters.com.au/stats/,HTML按钮为“下载CSV

import requests
from bs4 import BeautifulSoup
base_url = 'https://www.punters.com.au'
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3','referer': 'https://www.google.com/'}

# Make a request to the URL and parse the HTML content
response = requests.get(base_url + '/stats/', headers=headers)
soup = BeautifulSoup(response.content, 'html.parser')
# <a class="stats-csv" href="javascript:void(-1);">Download CSV</a>
csv = soup.find('a', class_="stats-csv")
print(csv)

这会找到按钮,但它是如何执行的呢?
Selenium似乎是唯一的选择,在匹配了ChromeDriver之后,我正在缓慢地前进,并添加了以下代码,该代码可以找到下载按钮,但尚未管理下载。

# import modules
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
driver = webdriver.Chrome() 
print("fetching csv button for {} ".format(base_url))
driver.get(base_url + '/stats/')
driver.implicitly_wait(2) # seconds
try:
  assert "Free Australian Horse Racing Statistics - Punters.com.au" in driver.title
  elem = driver.find_element(By.CLASS_NAME,"stats-csv").send_keys("webdriver" + Keys.ENTER)
except:
  print ("\n%Error-website: {}\n".format(base_url + '/stats/'))
nom7f22z

nom7f22z1#

因此,也许有一种方法可以在不使用Selenium的情况下做到这一点,但在我决定使用Selenium的评论之后,以下是解决方案:

import requests
driver = webdriver.Chrome() 
base_url = 'https://www.punters.com.au'
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3','referer': 'https://www.google.com/'}
driver.get(base_url + '/stats/')
driver.implicitly_wait(2) # seconds
# The next line is an assertion to confirm that title "<title>Free Australian Horse Racing Statistics - Punters.com.au</title>"
assert "Free Australian Horse Racing Statistics - Punters.com.au" in driver.title
# look for <a class="stats-csv" href="javascript:void(-1);">Download CSV</a>
elem = driver.find_element(By.CLASS_NAME,"stats-csv").click()  # click on Download CSV button
elem = driver.find_element(By.CLASS_NAME, "Save").click()
driver.close()

下载的文件为punters-com-au-downloaded-stats-jockeys-YYYY-MM-DD HH_MM_SS. csv。感谢您的帮助!

raogr8fs

raogr8fs2#

您可以使用Beautiful Soup和Requests库来实现这一点。

相关问题