网络抓取程序找不到我可以在浏览器中看到的元素

时间:2020-03-28 18:00:05

标签: python web-scraping beautifulsoup python-requests

我正在尝试使用Requests和BeautifulSoup在https://www.twitch.tv/directory/game/Dota%202上获取流的标题。我知道我的搜索条件正确,但是我的程序找不到我需要的元素。

以下是屏幕截图,显示了浏览器中源代码的相关部分:

Screenshot of the browser showing part of the webpage, as well as the source using the developer tools/web inspector.

HTML源文本:

<div class="tw-media-card-meta__title">
  <div class="tw-c-text-alt">
    <a class="tw-full-width tw-interactive tw-link tw-link--button tw-link--hover-underline-none tw-link--inherit" data-a-target="preview-card-title-link" href="/weplayesport_en">
      <div class="tw-align-items-start tw-flex">
        <h3 class="tw-ellipsis tw-font-size-5" title="NAVI vs HellRaisers | BO5 | ODPixel &amp; S4 | WeSave! Charity Play">NAVI vs HellRaisers | BO5 | ODPixel &amp; S4 | WeSave! Charity Play</h3>
      </div>
    </a>
  </div>
</div>

这是我的代码:

import requests
from bs4 import BeautifulSoup

req = requests.get("https://www.twitch.tv/directory/game/Dota%202")

soup = BeautifulSoup(req.content, "lxml")

title_elems = soup.find_all("h3", attrs={"title": True})

print(title_elems)

当我运行它时,title_elems只是一个空列表([])。

为什么我的程序找不到元素?

2 个答案:

答案 0 :(得分:7)

您感兴趣的元素是在初始页面加载后动态生成的,这意味着您的浏览器执行JavaScript,发出其他网络请求等以构建页面。请求只是一个HTTP库,因此不会执行这些操作。

您可以使用Selenium之类的工具,甚至可以分析网络流量以获取所需的数据并直接发出请求。

答案 1 :(得分:1)

您可以使用“请求”模块从该站点获取不同游戏的标题:

import re
import requests

url = "https://www.twitch.tv/directory/game/Dota%202"
link = "https://gql.twitch.tv/gql"

formdata = [{"operationName":"DirectoryRoot_Directory","variables":{"name":"dota 2"},"extensions":{"persistedQuery":{"version":1,"sha256Hash":"9f4f6ae67f21ee50b454fcf048691107a52bfe7907ead73b9427398e343ca319"}}},{"operationName":"Directory_DirectoryBanner","variables":{"name":"Dota 2"},"extensions":{"persistedQuery":{"version":1,"sha256Hash":"a64b0348103e054cbdb20c58de5fc05160da3f86c37c80263d7e6282f2577f54"}}},{"operationName":"DirectoryPage_Game","variables":{"name":"dota 2","options":{"sort":"RELEVANCE","recommendationsContext":{"platform":"web"},"requestID":"JIRA-VXP-2397","tags":[]},"sortTypeIsRecency":False,"limit":30},"extensions":{"persistedQuery":{"version":1,"sha256Hash":"f2ac02ded21558ad8b747a0b63c0bb02b0533b6df8080259be10d82af63d50b3"}}}]

with requests.Session() as s:
    s.headers['User-Agent'] = "Mozilla/5.0 (Windows NT 6.1; ) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36"
    res = s.get(url)
    s.headers['Client-Id'] = re.findall(r"Client-ID\":\"(.*?)\"",res.text)[0]
    res = s.post(link,json=formdata)
    for item in res.json()[2]['data']['game']['streams']['edges']:
        print(item['node']['title'])

您可能获得的结果类型:

PUBS 7.27 POG VIBE COOL FUN
Playing more 7.27
7.27 Pubs :) Climb to 9k
В новый сезон с новыми победами Custom Hero Chaos |  !discord 
Бобрый вечер !розыгрыш 
RERUN: Adroit vs Execration Game 1 - BTS Pro Series 2: SEA - Group Stage w/ MLP & johnxfire
(RU) Повтор | EGB.com Arena of Blood 
No Matter What
mid 5000-6000(5600) (!розыгрыш каждый день)
chegou a cam, pena que to parecendo um neanderthal