【问题标题】:'NoneType' Error While WebScraping StockTwitsWebScraping StockTwits 时出现“NoneType”错误
【发布时间】:2019-08-07 15:43:51
【问题描述】:

我正在尝试编写一个脚本来简单地读取和打印特定帐户监视列表上的所有代码。我已经设法导航到从 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 设置)

这是我的错误:

【问题讨论】:

    标签: python web-scraping stocktwits


    【解决方案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)
    

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

    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)
    

    【讨论】:

    • 只有通过json获取吗?
    • 这是最简单的方法。所有的股票都在那里。更昂贵的开销是使用浏览器自动化,例如 selenium,
    • 有没有办法以某种方式访问​​ HTML 中其他任何地方末尾的六位数字?试图使这项工作适用于一小部分人。
    • ids = [i['id'] for i in r['watchlist']['symbols']] 它们存在于 json 中。假设这就是你的意思。
    • 谢谢,最后你使用的 [i['id'] for i... 形式是什么。显然这是一个 for 循环,但我怎样才能学习如何使用这种类型的表单
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-04
    • 1970-01-01
    • 2017-04-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多