【问题标题】:I don't get any output when I scrape this刮这个时我没有得到任何输出
【发布时间】:2021-08-23 05:28:15
【问题描述】:

我想把我在以下website的打字测试中的错别字刮掉。

这是我使用的代码

from bs4 import BeautifulSoup
import requests

header = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36"
}

n = 798
url = f"https://data.typeracer.com/pit/result?id=|tr:_cephas_|{n}"
page = requests.get(url, headers = header)

soup = BeautifulSoup(page.content, 'lxml')

for List in soup.select("div.replayWord"):
    print(List.get_text(strip=True))

我使用了不同的选择器,还使用了 find() 和 find_all() 函数。但我无法得到这个的任何输出。请帮我找出我的问题。

【问题讨论】:

  • 您要查找的内容是通过JS 动态呈现的,因此使用bs4 模块您将无法提取它,尝试使用selenium 可能会奏效!
  • 你是怎么找到@BhavyaParikh的?
  • 当您打印 soup 时,您可以通过搜索元素手动找到,如果您刷新向下滚动到分析部分,甚至可以从站点中找到,加载需要几秒钟。

标签: python-3.x web-scraping beautifulsoup python-requests


【解决方案1】:

有一个 python 库旨在支持您的需求。看看requests_html

安装它:

pip install requests_html

添加这个:

 from requests_html import HTMLSession

那么这就是你的解决方案:

from requests_html import HTMLSession
from bs4 import BeautifulSoup
#import requests

header = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36"
}

n = 798
url = f"https://data.typeracer.com/pit/result?id=|tr:_cephas_|{n}"

session = HTMLSession()
r = session.get(url, headers = header)
r.html.render(timeout=60)
replayWords = r.html.find("div.replayWord")

for word in replayWords:
    print(word.text)

请注意,第一次运行它时,它会下载 chromium 作为渲染代理 - 这可能需要一分钟。

这个库在我机器上的render 上似乎也很慢。我不确定这是该站点还是我的笔记本电脑在休息日,但是,如果您可以忍受这种延迟,则输出是:

spot
intend
must
known;
against
possible
points;
forces
being
many

【讨论】:

    猜你喜欢
    • 2021-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-30
    • 2018-05-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多