Skip to main content
 首页 » 编程设计

Python 网页抓取查询

2024年12月31日9JeffreyZhao

我已经编写了我的第一个 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)) 

File "F:/System/Python/dividend.py", line 9, in table = soup.select("table#Dividend History")[0]

IndexError: list index out of range

请您参考如下方法:

这不是直接的回答,而是建议。根据您的需要,您引用的网站基于 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 循环遍历它。