【发布时间】:2017-12-02 11:34:47
【问题描述】:
我正在尝试获取链接的 URL,以在特定时间范围内从 Yahoo Finance 下载资产的历史数据。 1999 年 1 月 1 日至今。
我想获得这个(从数据表上方的“下载数据”链接):
"https://query1.finance.yahoo.com/v7/finance/download/XLB?period1=915177600&period2=1498633200&interval=1d&events=history&crumb=iX6bJ6LfGxc"
我正在使用 BeautifulSoup 并且遇到了包含 href 的所需标签未显示在 html 中的问题。起初,我认为 BeautifulSoup 只是在尝试使用 find_all('a') 并遍历子/后代没有得到任何结果后无法正常工作。但是当我对 html 进行文本转储时,html 元素(以及父元素中的所有其他内容)都不存在。 有人可以解释发生了什么吗?下面列出了我目前正在使用的内容。
from bs4 import BeautifulSoup
import datetime as dTime
import requests
"""
asset = "Materials"
assetSignal = "XLB"
today = dTime.datetime.now()
startTime = str(int(dTime.datetime(1999, 1, 1, 0, 0, 0).timestamp()))
endTime = str(int(dTime.datetime(today.year, today.month, today.day, 0, 0, 0).timestamp()))
url = "https://finance.yahoo.com/quote/" + assetSignal + "/history?period1=" + startTime + "&period2=" + endTime + "&interval=1d&filter=history&frequency=1d"
"""
url = "https://finance.yahoo.com/quote/XLB/history?period1=915177600&period2=1498633200&interval=1d&filter=history&frequency=1d"
page = requests.get(url)
data = page.content
#soup = BeautifulSoup(data, "html.parser")
soup = BeautifulSoup(data, "lxml")
#soup = BeautifulSoup(data, "xml")
#soup = BeautifulSoup(data, "html5lib")
#Link not found
for link in soup.find_all("a"):
print(link.get("href"))
#Span is empty?
span = soup.find(class_="Fl(end) Pos(r) T(-6px)")
print(span)
print(span.string)
print(span.contents)
for child in span.children:
print(child)
#Other span has children. Target span doesn't
div = soup.find(class_="C($finDarkGray) Mt(20px) Mb(15px)")
print(div)
for child in div.descendants:
print(child)
#Is the tag even there?
with open("soup.txt", "w") as file:
file.write(page.text)
【问题讨论】:
-
这段代码能运行吗?因为
url = https://finance.yahoo.com/quote/XLB/history?period1=915177600&period2=1498633200&interval=1d&filter=history&frequency=1d在我看来很可疑。 -
代码有效,只需将该网址放在引号中,但实际上下载链接在soup 结果中不可用。看起来链接是javascript,BeautifulSoup不执行Javascript,所以如果你用BeautifulSoup抓取,任何通过JS传递或呈现的数据都将不可用。可能需要研究 selenium 或 phantomjs
标签: python html beautifulsoup html-parsing