【发布时间】:2022-01-06 12:23:57
【问题描述】:
一段时间以来,我一直在尝试从 iShares.com 为一个正在进行的项目抓取 ETF 数据。我正在尝试为多个网站创建网络抓取工具,但它们都是相同的。基本上我遇到了两个问题:
-
我不断收到错误消息:“AttributeError: 'NoneType' object has no attribute 'tr'”虽然我很确定我选择了正确的表。
-
当我查看某些网站上的“检查元素”时,我必须单击“显示更多”才能查看所有行的代码。
我不是计算机科学家,但我尝试了许多不同的方法,但遗憾的是都没有成功,所以我希望你能提供帮助。
可以在“Holdings”下的 URL 中找到该表。或者,可以在以下路径下找到它:
JS 路径:
代码:
import requests
import pandas as pd
from bs4 import BeautifulSoup
urls = [
'https://www.ishares.com/uk/individual/en/products/251382/ishares-msci-world-minimum-volatility-ucits-etf'
]
all_data = []
for url in urls:
print("Loading URL {}".format(url))
# load the page into soup:
soup = BeautifulSoup(requests.get(url).content, "html.parser")
# find correct table:
tbl = soup.select_one(".allHoldingsTable")
# remove the first row (it's not header):
tbl.tr.extract()
# convert the html to pandas DF:
df = pd.read_html(str(tbl),thousands='.', decimal=',')[0]
# move the first row to header:
df.columns = map(lambda x: str(x).replace("*", "").strip(), df.loc[0])
df = df.loc[1:].reset_index(drop=True).rename(columns={"nan": "Name"})
df["Company"] = soup.h1.text.split("\n")[0].strip()
df["URL"] = url
all_data.append(df.loc[:, ~df.isna().all()])
df = pd.concat(all_data, ignore_index=True)
print(df)
from openpyxl import load_workbook
path= '/Users/karlemilthulstrup/Downloads/ishares.xlsx'
book = load_workbook(path ,read_only = False, keep_vba=True)
writer = pd.ExcelWriter(path, engine='openpyxl')
writer.book = book
df.to_excel(writer, index=False)
writer.save()
writer.close()
【问题讨论】:
-
你最好在“查看页面源代码”而不是“检查元素”中搜索 bs4 将不会看到已被 javascript 添加或修改的元素。它只会看到原始页面源
-
如果您在浏览器中禁用 javascript 然后查看页面,您将看到馆藏表中没有数据。它只有一个 thead 元素
-
@ChrisDoyle 出于好奇,是否有机会通过 bs4 抓取添加/修改的元素?
-
@ChrisDoyle 非常感谢您花时间研究它。我无法刮掉它是有道理的。有没有像wolfstter问的那样解决它?否则,我想我应该走 API 路线。
标签: python pandas web-scraping beautifulsoup