簡體   English   中英

Python 網頁抓取查詢

[英]Python web scraping query

我已經編寫了我的第一個 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:列表索引超出范圍

這不是直接的答案,而是建議。 根據您的需要,您所引用的網站基於 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 循環遍歷它。

這個頁面的布局似乎是基於表格的,很多表格。 您的代碼正在嘗試查找 ID 為“股息”的表,該表不存在。

這是經過一些調整后的代碼。 它找到包含數據的行,然后從行中提取數據:

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

driver = webdriver.Chrome()
driver.get("https://www.dividendchannel.com/history/?symbol=ibm")

soup = BeautifulSoup(driver.page_source,"lxml")
driver.quit()

dividend_rows = soup.select("div#divvytable")[0].find_all("tr")

for row in dividend_rows:
    columns = list(row.stripped_strings)
    if len(columns) != 2:
        continue
    print("date: {} amount: {}".format(columns[0], columns[1]))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM