python - 如何使用 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)
谢谢你的帮助
解决方案
该表是从不同的 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%)
推荐阅读
- java - 将浮点值从一个 servlet 传递到另一个 servlet 时出现 servlet 问题
- javascript - 在命令之外使用 discord.js 模块
- c# - 可以在 Unity3D 中创建更高效的寻的导弹系统吗?
- c# - 如何通过 IEnumerable 返回数据
功能 - xml - 使用自定义功能区关闭并重新打开文档后,Word 会话功能区会发生什么情况?
- android - admob 广告类型是否存在收入不平等
- c# - Visual Studio C# 交换字符
- algorithm - 删除数组中的每个奇数索引,直到数组中的元素数变为 1
- css - 如何在 blogger.com 网站中禁用动态视图下拉列表?
- apache - 通过 apache Web 服务器提供的 IE11 浏览器中未加载 JPEG 图像