我一直在学习如何使用Pandas抓取网页,我遇到了一堵墙,我无法提取内部的特定数据。
下面是Pandas正在解析的html:
<tr data-country="Bulgaria">
<td><i aria-hidden="true" class="
circle-country-flags-22 flags-22-bulgaria display-inline-block"></i>
<a title="Bulgaria Economic Calendar" href="https://www.myfxbook.com/forex-economic-
calendar/bulgaria">Bulgaria</a></td>
<td>BNB</td>
<td> <a title="Bulgaria Interest Rates" href="https://www.myfxbook.com/forex-economic-
calendar/bulgaria/interest-rate-decision">Bulgarian National Bank</a> </td>
<td class="green"> 2.17% </td>
<td>1.82%</td>
<td> 35bp </td>
<td data-custom-date="2023-04-28 00:00:00.0">Apr 28, 2023</td>
<td data-custom-date="2023-05-29 10:00:00.0">1 day</td>
</tr>
下面是我的响应数组:
{'Central Bank': 'Bulgarian National Bank',
'Change': '35bp',
'Country': 'Bulgaria',
'Current Rate': '2.17%',
'Last Meeting': 'Apr 28, 2023',
'Next Meeting': '1 day',
'Previous Rate': '1.82%',
'Unnamed: 1': 'BNB'}
这是我专门看的“1天”这一行
当我试图将“2023-05-29 10:00:00.0”解析为响应而不是“1 day”时
以下是我迄今为止为此创建的代码:
import pandas as pd
import requests
import pprint
from datetime import datetime, timedelta
url = "https://www.myfxbook.com/forex-economic-calendar/interest-rates"
r = requests.get(url)
tables = pd.read_html(r.text) # this parses all the tables in webpages to a list
# Extract the first table from the list of parsed tables
parsed_table = tables[0]
# Convert DataFrame to list of dictionaries
list_of_dicts = parsed_table.to_dict(orient='records')
# Print the list of dictionaries
data = []
for row in list_of_dicts:
data.append(row)
pp = pprint.PrettyPrinter(depth=4)
pp.pprint(data)
我一直在搜索互联网,但还没有能够找到一个解决方案,到目前为止,我如何做到这一点,所以任何帮助将不胜感激这一点。
1条答案
按热度按时间tsm1rwdh1#
简单的解决方案是使用HTML解析器(如
beautifulsoup
)并替换<td>
标记的文本。然后使用pd.read_html
获取 Dataframe :图纸: