我想從http://www.dividend.com/dividend-stocks/的第三個表中獲取數據。 這裏是代碼,我需要一些幫助。使用BeautifulSoup從網頁獲取特定表格
import requests
from bs4 import BeautifulSoup
url = "http://www.dividend.com/dividend-stocks/"
r = requests.get(url)
soup = BeautifulSoup(r.content, "html5lib")
# Skip first two tables
tables = soup.find("table")
tables = tables.find_next("table")
tables = tables.find_next("table")
row = ''
for td in tables.find_all("td"):
if len(td.text.strip()) > 0:
row = row + td.text.strip().replace('\n', ' ') +','
# Handle last column in a row, remove extra comma and add new line
if td.get('data-th') == 'Pay Date':
row = row[:-1] + '\n'
print(row)
但代碼的輸出是這樣的:
AAPL,Apple Inc.,1.76%,$143.39,$2.52,5/11,5/18
GE,General Electric,3.32%,$28.91,$0.96,6/15,7/25
XOM,Exxon Mobil,3.71%,$83.03,$3.08,5/10,6/9
CVX,Chevron Corp,4.01%,$107.72,$4.32,5/17,6/12
BP,BP PLC ADR,6.66%,$35.72,$2.38,5/10,6/23
我做了什麼錯?謝謝你的幫助!
請給你的問題一個更具體的描述它的標題。這裏的大多數問題都是關於無法按預期工作的代碼。 – Barmar
@Barmar謝謝指出。下次我會更加小心。 – fuzzyworm
@fuzzyworm看起來您將它們保存爲CSV格式,但有3家公司名稱中帶有逗號,因此您可能希望將公司名稱放在雙引號內。 'Qualcomm,Inc','Banco Santander,S.A.','Activision Blizzard,Inc.' –