首页 > 解决方案 > 如何从 tiktok 网站获取关注者数量?

问题描述

这是我第一次编写 python 脚本。我正在尝试从 tiktok 网站中提取关注者数量并将其用作字符串。我从进入 chrome 中的 Inspect 窗口得到选择器路径,单击关注者计数,然后右键单击“17M”(在此示例中)以保存选择器路径。这昨天工作得很好,然后突然停止了,现在无论我尝试什么,我都无法从这个页面获得“17M”。我正在使用 requests-html,但肯定会尝试美味的汤或您有的任何其他推荐!

from requests_html import HTMLSession
session = HTMLSession()
url = "https://www.tiktok.com/@terrycrews"
r = session.get(url)
sel = '#main > div.jsx-2773227880.main-body.page-with-header.middle.em-follow > div.jsx- 2938571814.share-layout.compact.middle > div > header > h2.count-infos > div:nth-child(2) > strong'
followers = r.html.find(sel, first=True).text
print(followers)

我得到的当前错误是 AttributeError: 'NoneType' object has no attribute 'text' 运行此代码时。我希望得到17M.

我希望您能提供任何帮助。谢谢!

标签: pythonhtmlweb-scrapingbeautifulsouppython-requests-html

解决方案


尝试指定User-AgentHTTP 标头:

import requests
from bs4 import BeautifulSoup

url = "https://www.tiktok.com/@terrycrews"

headers = {
    "User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:90.0) Gecko/20100101 Firefox/90.0"
}

soup = BeautifulSoup(requests.get(url, headers=headers).content, "html.parser")
print(soup.select_one('[title="Followers"]').text)

印刷:

17M

推荐阅读