擅长:python、mysql、java
<p>您试图从中获取的页面正在使用JavaScript异步填充DOM。您可以期望BeautifulSoup不适用于这样的页面,因为BeautifulSoup只能看到在服务器向您提供文档时直接烘焙到HTML中的内容</p>
<p>如果在浏览器中查看页面并记录网络流量,您将看到对各种REST API端点发出的多个请求,其中一个端点<code>/InvestaApi/Stock/ViewStock</code>,并将“股票代码”作为查询字符串参数。该端点的响应是JSON,包含您试图获取的信息。您只需模拟HTTP GET请求:</p>
<pre><code>def get_price(stock_code):
import requests
url = "https://webapi.investagrams.com/InvestaApi/Stock/ViewStock"
params = {
"stockCode": stock_code,
"defaultExchangeType": "1",
"cv": "1622292000-0-"
}
headers = {
"accept": "application/json",
"accept-encoding": "gzip, deflate",
"referer": "https://www.investagrams.com/",
"user-agent": "Mozilla/5.0"
}
response = requests.get(url, params=params, headers=headers)
response.raise_for_status()
return response.json()["LatestStockHistory"]["Last"]
def main():
print(get_price("ac"))
return 0
if __name__ == "__main__":
import sys
sys.exit(main())
</code></pre>
<p>输出:</p>
<pre><code>779
>>>
</code></pre>