首页 > 解决方案 > Python网页抓取查询

问题描述

我已经编写了我的第一个 python 代码来从网络上抓取股息历史表,但是 soup.select 语句似乎没有选择任何内容并导致索引错误。

请问有什么解决方法的建议吗?

from selenium import webdriver
from bs4 import BeautifulSoup
import pandas as pd

driver = webdriver.Chrome(executable_path='F:\PythonApps\ChromeDriver\ChromeDriver.exe')
driver.get("https://www.dividendchannel.com/history/?symbol=ibm")
soup = BeautifulSoup(driver.page_source,"lxml")
driver.quit()
table = soup.select("table#Dividend History")[0]
print(table)
list_row =[[tab_d.text.strip().replace("\n","") for tab_d in 
item.select('th,td')] for item in table.select('tr')]

for data in list_row[:2]:
    print(' '.join(data))

文件“F:/System/Python/dividend.py”,第 9 行,在 table = soup.select("table#Dividend History")[0] 中

IndexError:列表索引超出范围

标签: pythonbeautifulsoup

解决方案


这不是一个直接的答案,而是一个建议。根据您的需要,您所引用的网站基于 IP 的使用量有限,只能访问 6 次。看看免费的股息 api(不是广告)-> IEX API

如果您选择使用它,它可能会使您的应用程序更加高效。使用 JSON 数据然后转换为数据帧(PANDAS)或通过 JavaScript 发布到前端要容易得多。

这是过去 5 年申请的示例电话->

https://api.iextrading.com/1.0/stock/aapl/dividends/5y

您将使用 requests.get(url, params).json() 并通过一个简单的 for 循环遍历它。


推荐阅读