如何单击网站中的CSV按钮并用python下载数据

2024-09-28 05:18:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试从以下网站下载CSV和JSON数据:https://worldpopulationreview.com/countries/countries-by-gdp/#worldCountries

如何模拟点击csv文件

import pandas as pd
import requests
from lxml import html,etree

url = "https://worldpopulationreview.com/countries/countries-by-gdp/#worldCountries"

# now I am not sure, how to click csv button of actual website
# also I am not sure how it will download the csv file
# to DOWNLOADS as like when I click the page

我可以刮网页,但我想学习点击按钮

import pandas as pd
import requests

url = "https://worldpopulationreview.com/countries/countries-by-gdp/#worldCountries"

r = requests.get(url)
df = pd.read_html(r.text)[0]
df.to_csv('data.csv')

Tags: csvtohttpsimportcomurlpandasby
2条回答

你需要下载pip install selenium 如果使用Chrome,请在此处下载Chrome驱动程序-Chrome driver。然后查找按钮/链接的xpath,我使用inspect元素查找xpath:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Chrome(executable_path='/Users/xxx/Downloads/chromedriver-1')
driver.get('https://worldpopulationreview.com/countries/countries-by-gdp')#put here the adress of your page
btn = driver.find_element_by_xpath('/html/body/div[1]/div/div[1]/div[2]/div[2]/div[1]/div/div/div/div[2]/div[1]/a[2]')
btn.click()
df = pd.read_csv('/Users/xxx/Downloads/data.csv')
print(df.head())
driver.close()

   rank         country        imfGDP           unGDP  gdpPerCapita          pop
0     1   United States  2.219812e+13  18624475000000    67063.2695   331002.651
1     2           China  1.546810e+13  11218281029298    10746.7828  1439323.776
2     3           Japan  5.495420e+12   4936211827875    43450.1405   126476.461
3     4         Germany  4.157120e+12   3477796274497    49617.1450    83783.942
4     6  United Kingdom  2.927080e+12   2647898654635    43117.5725    67886.011

要查找xpath,请执行以下操作: Xpath

相关问题 更多 >

    热门问题