首页 > 解决方案 > 想用 selenium 在页面上刮一张桌子

问题描述

我想将页面上的表格刮到数据框中,其中列名称为“合同”和“资金费率”。(https://www.binance.com/en/futures/funding-history/1

这是我到目前为止尝试过的,但仍然无法解决。感谢是否有人可以帮助我解决这个问题。

import time

import pandas as pd

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

options = Options()

options.headless = True
driver = webdriver.Chrome(options=options)

driver.get("https://www.binance.com/cn/futures/funding-history/0")
time.sleep(5)
# headers = driver.find_elements_by_xpath('//*[@class="tablesorter-headerRow"][2]/th/div')
table = driver.find_element_by_xpath('//*[@id="bnc-table-tbody"]')

但它给我带来了一些错误。

标签: pythonseleniumweb-scraping

解决方案


xPath 选择器应该是://*[@class="bnc-table-tbody"]

HTML:

示例

然后您可以迭代表行并转换为DataFrame

table = driver.find_element_by_xpath('//*[@class="bnc-table-tbody"]')
data = []
for tr in table.find_elements_by_xpath('tr'):
    columns = tr.find_elements_by_xpath('td')
    data.append({
        'Contract': columns[0].text,
        'Funding Rate': columns[2].text
    })
# Convert lits of dictionaries into a dataframe
df = pd.DataFrame(data)

推荐阅读