首页 > 解决方案 > 如何使用 Python 和 BeautifulSoup 从本网站提取表格

问题描述

我想从本网站上的 1 个表中提取数据,但我无法找到其中任何一个。我已经检查了一些类似问题的答案,但它们似乎都不起作用。

那是我的代码

from bs4 import BeautifulSoup
import requests

hdr = {'User-Agent': 'Mozilla/5.0'}
url = "https://www.home.saxo/en-gb/insights/tools/fx-options-risk-tool/tool-details" 

response = requests.get(url,headers=hdr)
soup = BeautifulSoup(response.content, "html.parser")

#find all tables

soup.find_all('tables')

我对其中一个特别感兴趣,并在代码下方提取其标题:

vol_table = soup.find("table", attrs={"class": "volTable"})
vol_table_data = vol_table.tbody.find_all("tr") 

# Get all the headings of Lists
headings = []
for td in vol_table_data[0].find_all("td"):
    # remove any newlines and extra spaces from left and right
    headings.append(td.b.text.replace('\n', ' ').strip())

print(headings)

谢谢你的帮助

标签: pythonweb-scrapingbeautifulsoup

解决方案


该表是从不同的 URL 加载的。使用此示例从第一个表中加载数据:

import requests
from bs4 import BeautifulSoup


url = 'https://fxowebtools.saxobank.com/otc.html'
soup = BeautifulSoup(requests.get(url).content, 'html.parser')

for pair, spot in zip(soup.select('td.volPair'), soup.select('td.spot')):
    print(pair.text, spot.text)

印刷:

EURUSD 1.1836 (0.34%)
USDJPY 104.33 (-0.25%)
GBPUSD 1.2968 (0.74%)
AUDUSD 0.7285 (-0.22%)
USDCAD 1.3194 (-0.10%)
USDCHF 0.9104 (-0.02%)
EURJPY 123.49 (0.08%)
EURGBP 0.9128 (-0.41%)
EURCHF 1.0776 (0.32%)
XAUUSD 1948.13 (0.28%)
XAGUSD 26.9086 (0.24%)
EURUSD 1.1836 (0.34%)
USDJPY 104.33 (-0.25%)
GBPUSD 1.2968 (0.74%)
AUDUSD 0.7285 (-0.22%)
USDCAD 1.3194 (-0.10%)
USDCHF 0.9104 (-0.02%)
EURJPY 123.49 (0.08%)
EURGBP 0.9128 (-0.41%)
EURCHF 1.0776 (0.32%)
XAUUSD 1948.13 (0.28%)
XAGUSD 26.9086 (0.24%)

推荐阅读