本指南演示了如何使用 Python、请求库和 lxml 库从雅虎财经中抓取数据。雅虎财经提供股票价格和市场趋势等大量金融数据,这些数据对于实时市场分析、金融建模和制定自动投资策略至关重要。
该过程包括发送 HTTP 请求以检索网页内容,解析收到的 HTML,并使用 XPath 表达式提取特定数据。这种方法可以高效、有针对性地提取数据,使用户能够动态地访问和利用财务信息。
我们将使用以下 Python 库:
开始之前,请确保已安装这些库:
pip install requests
pip install lxml
下面,我们将以循序渐进的方式探讨解析过程,并提供完整的代码示例,使其更加清晰易懂。
网络搜刮的第一步是向目标 URL 发送 HTTP 请求。我们将使用请求库来完成这项工作。在请求中包含适当的标头以模拟真实浏览器至关重要,这有助于绕过基本的反僵尸措施。
import requests
from lxml import html
# 目标 URL
url = "https://finance.yahoo.com/quote/AMZN/"
# 模拟真实浏览器的页眉
headers = {
'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
'accept-language': 'en-IN,en;q=0.9',
'cache-control': 'no-cache',
'dnt': '1',
'pragma': 'no-cache',
'priority': 'u=0, i',
'sec-ch-ua': '"Not)A;Brand";v="99", "Google Chrome";v="127", "Chromium";v="127"',
'sec-ch-ua-mobile': '?0',
'sec-ch-ua-platform': '"Linux"',
'sec-fetch-dest': 'document',
'sec-fetch-mode': 'navigate',
'sec-fetch-site': 'none',
'sec-fetch-user': '?1',
'upgrade-insecure-requests': '1',
'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36',
}
# 发送 HTTP 请求
response = requests.get(url, headers=headers)
标题和价格:
更多详情:
下面是我们用来提取不同财务数据的 XPath 表达式:
# 解析 HTML 内容
parser = html.fromstring(response.content)
# 使用 XPath 提取数据
title = ' '.join(parser.xpath('//h1[@class="yf-3a2v0c"]/text()'))
live_price = parser.xpath('//fin-streamer[@class="livePrice yf-mgkamr"]/span/text()')[0]
date_time = parser.xpath('//div[@slot="marketTimeNotice"]/span/text()')[0]
open_price = parser.xpath('//ul[@class="yf-tx3nkj"]/li[2]/span[2]/fin-streamer/text()')[0]
previous_close = parser.xpath('//ul[@class="yf-tx3nkj"]/li[1]/span[2]/fin-streamer/text()')[0]
days_range = parser.xpath('//ul[@class="yf-tx3nkj"]/li[5]/span[2]/fin-streamer/text()')[0]
week_52_range = parser.xpath('//ul[@class="yf-tx3nkj"]/li[6]/span[2]/fin-streamer/text()')[0]
volume = parser.xpath('//ul[@class="yf-tx3nkj"]/li[7]/span[2]/fin-streamer/text()')[0]
avg_volume = parser.xpath('//ul[@class="yf-tx3nkj"]/li[8]/span[2]/fin-streamer/text()')[0]
# 打印提取的数据
print(f"Title: {title}")
print(f"Live Price: {live_price}")
print(f"Date & Time: {date_time}")
print(f"Open Price: {open_price}")
print(f"Previous Close: {previous_close}")
print(f"Day's Range: {days_range}")
print(f"52 Week Range: {week_52_range}")
print(f"Volume: {volume}")
print(f"Avg. Volume: {avg_volume}")
雅虎财经等网站通常采用反僵尸措施来防止自动搜索。为避免被阻止,您可以使用代理和旋转页眉。
代理服务器是您的机器和目标网站之间的中介。它有助于掩盖您的 IP 地址,使网站更难发现您正在进行搜刮。
# 使用 IP 授权模式代理的示例
proxies = {
"http": "http://your.proxy.server:port",
"https": "https://your.proxy.server:port"
}
response = requests.get(url, headers=headers, proxies=proxies)
旋转 User-Agent 标头是另一种避免被检测的有效方法。你可以使用一个常用 User-Agent 字符串列表,每次请求时随机选择一个。
import random
user_agents = [
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:76.0) Gecko/20100101 Firefox/76.0",
# 在此处添加更多 User-Agent 字符串
]
headers["user-agent"]: random.choice(user_agents)
response = requests.get(url, headers=headers)
最后,您可以将刮擦的数据保存到 CSV 文件中,以供日后使用。这对于存储大型数据集或离线分析数据特别有用。
import csv
# 要保存的数据
data = [
["URL", "Title", "Live Price", "Date & Time", "Open Price", "Previous Close", "Day's Range", "52 Week Range", "Volume", "Avg. Volume"],
[url, title, live_price, date_time, open_price, previous_close, days_range, week_52_range, volume, avg_volume]
]
# 保存为 CSV 文件
with open("yahoo_finance_data.csv", "w", newline="") as file:
writer = csv.writer(file)
writer.writerows(data)
print("Data saved to yahoo_finance_data.csv")
下面是完整的 Python 脚本,它集成了我们讨论过的所有步骤。其中包括发送带标头的请求、使用代理、使用 XPath 提取数据以及将数据保存到 CSV 文件。
import requests
from lxml import html
import random
import csv
# URL 扫描示例
url = "https://finance.yahoo.com/quote/AMZN/"
# 旋转标题的用户代理字符串列表
user_agents = [
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:76.0) Gecko/20100101 Firefox/76.0",
# Add more User-Agent strings here
]
# 模拟真实浏览器的页眉
headers = {
'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
'accept-language': 'en-IN,en;q=0.9',
'cache-control': 'no-cache',
'dnt': '1',
'pragma': 'no-cache',
'priority': 'u=0, i',
'sec-ch-ua': '"Not)A;Brand";v="99", "Google Chrome";v="127", "Chromium";v="127"',
'sec-ch-ua-mobile': '?0',
'sec-ch-ua-platform': '"Linux"',
'sec-fetch-dest': 'document',
'sec-fetch-mode': 'navigate',
'sec-fetch-site': 'none',
'sec-fetch-user': '?1',
'upgrade-insecure-requests': '1',
'User-agent': random.choice(user_agents),
}
# 使用代理的示例
proxies = {
"http": "http://your.proxy.server:port",
"https": "https://your.proxy.server:port"
}
# 发送带有标头和可选代理的 HTTP 请求
response = requests.get(url, headers=headers, proxies=proxies)
# 检查请求是否成功
if response.status_code == 200:
# 解析 HTML 内容
parser = html.fromstring(response.content)
# 使用 XPath 提取数据
title = ' '.join(parser.xpath('//h1[@class="yf-3a2v0c"]/text()'))
live_price = parser.xpath('//fin-streamer[@class="livePrice yf-mgkamr"]/span/text()')[0]
date_time = parser.xpath('//div[@slot="marketTimeNotice"]/span/text()')[0]
open_price = parser.xpath('//ul[@class="yf-tx3nkj"]/li[2]/span[2]/fin-streamer/text()')[0]
previous_close = parser.xpath('//ul[@class="yf-tx3nkj"]/li[1]/span[2]/fin-streamer/text()')[0]
days_range = parser.xpath('//ul[@class="yf-tx3nkj"]/li[5]/span[2]/fin-streamer/text()')[0]
week_52_range = parser.xpath('//ul[@class="yf-tx3nkj"]/li[6]/span[2]/fin-streamer/text()')[0]
volume = parser.xpath('//ul[@class="yf-tx3nkj"]/li[7]/span[2]/fin-streamer/text()')[0]
avg_volume = parser.xpath('//ul[@class="yf-tx3nkj"]/li[8]/span[2]/fin-streamer/text()')[0]
# 打印提取的数据
print(f"Title: {title}")
print(f"Live Price: {live_price}")
print(f"Date & Time: {date_time}")
print(f"Open Price: {open_price}")
print(f"Previous Close: {previous_close}")
print(f"Day's Range: {days_range}")
print(f"52 Week Range: {week_52_range}")
print(f"Volume: {volume}")
print(f"Avg. Volume: {avg_volume}")
# 将数据保存为 CSV 文件
data = [
["URL", "Title", "Live Price", "Date & Time", "Open Price", "Previous Close", "Day's Range", "52 Week Range", "Volume", "Avg. Volume"],
[url, title, live_price, date_time, open_price, previous_close, days_range, week_52_range, volume, avg_volume]
]
with open("yahoo_finance_data.csv", "w", newline="") as file:
writer = csv.writer(file)
writer.writerows(data)
print("Data saved to yahoo_finance_data.csv")
else:
print(f"Failed to retrieve data. Status code: {response.status_code}")
使用 Python 搜刮雅虎财经数据是一种自动收集财经数据的强大方法。通过使用 requests 和 lxml 库以及适当的标头、代理和反僵尸措施,您可以高效地抓取和存储股票数据以供分析。本指南涵盖了基础知识,但请记住,在刮擦网站时一定要遵守法律和道德准则。
Мы получили вашу заявку!
Ответ будет отправлен на почту в ближайшее время.
С уважением proxy-seller.com!
评论: 0