Web废弃StockTwits时出现“ NoneType”错误

时间:2019-08-07 15:43:51

标签: python web-scraping stocktwits

我正在尝试编写一个脚本,该脚本仅读取并打印特定帐户监视列表上的所有报价器。我设法导航到从HTML打印用户名的页面,现在我想使用find()查找其位置,然后使用.find_all()查找每个报价,但每次都打印他跟随的所有报价我尝试使用find()命令导航到返回“ NoneType”的监视列表代码。

这是我的代码:

import requests
import xlwt
from xlutils.copy import copy
from xlwt import Workbook
import xlrd
import urllib.request as urllib2
from bs4 import BeautifulSoup

hisPage = ("https://stocktwits.com/GregRieben/watchlist")

page = urllib2.urlopen(hisPage)

soup = BeautifulSoup(page, "html.parser")

his_name = soup.find("span", {"class":"st_33aunZ3 st_31YdEUQ st_8u0ePN3 st_2mehCkH"})

name = his_name.text.strip()
print(name)

watchlist = soup.find("div", {"class":"st_16989tz"})

tickers = watchlist.find_all('span', {"class":"st_1QzH2P8"})

print(type(watchlist))
print(len(watchlist))

在这里,我需要突出显示的值(LSPD.CA)以及之后的所有其他值(它们都具有完全相同的HTML设置)

highlighted value

这是我的错误:

Error

1 个答案:

答案 0 :(得分:1)

该内容是通过api调用动态添加的(因此,您的请求中不会出现在原始URL中,而DOM不会像使用浏览器时那样被更新)。您可以在网络流量中找到监视列表的API调用。它返回json。您可以从中提取想要的内容。

import requests

r = requests.get('https://api.stocktwits.com/api/2/watchlists/user/396907.json').json()
tickers = [i['symbol'] for i in r['watchlist']['symbols']]
print(tickers)

如果您需要获取要传递给API的用户ID,则它会在许多地方出现,以响应您的原始网址。我正在使用正则表达式从脚本标签中获取

import requests, re

p = re.compile(r'subjectUser":{"id":(\d+)')

with requests.Session() as s:
    r = s.get('https://stocktwits.com/GregRieben/watchlist')
    user_id = p.findall(r.text)[0]
    r = s.get('https://api.stocktwits.com/api/2/watchlists/user/' + user_id + '.json').json()
    tickers = [i['symbol'] for i in r['watchlist']['symbols']]
print(tickers)
相关问题