You need to enable JavaScript to run this app. 使用BeautifulSoup爬取10fastfingers单词列表无法获取内容求助
优惠活动
大模型
产品
解决方案
定价
更多

使用BeautifulSoup爬取10fastfingers单词列表无法获取内容求助

问题描述

需要提取10fastfingers打字测试页面中,测试环节需要用户输入的完整单词集合。已通过HTML结构定位到id为wordlist的对应节点,但无法提取节点内的实际单词内容。
原有实现代码如下:

from bs4 import BeautifulSoup
from urllib.request import urlopen , Request
import requests

url = "https://10fastfingers.com/typing-test/german"
page = urlopen(Request(url, headers={'User-Agent': 'Mozilla'})).read()
# page = requests.get(url).text
soup = BeautifulSoup(page, "lxml")

match = soup.find("div", class_="row main-layout")
wordlist = match.find("div",  {'id': 'wordlist'})
with open("page content.txt", "w") as file:
    file.write(str(page))
print(wordlist)
问题原因

id="wordlist"节点内的单词没有以独立子标签的形式存储,而是用|作为分隔符拼接成一整段纯文本,直接存放在该节点的文本内容中。同时该节点默认设置了display:none的隐藏样式,直接打印标签对象无法直观看到完整文本,且原有代码仅定位到了标签对象,没有做文本提取和分割处理。

解决方案
  • 定位到wordlist节点后,直接读取节点的.text属性,拿到拼接好的整段单词串
  • 用|作为分隔符切割字符串,即可得到按测试顺序排列的完整单词列表
  • 补全常规浏览器请求头,避免被站点反爬策略拦截,返回不含有效内容的异常页面

修正后的可运行代码:

from bs4 import BeautifulSoup
from urllib.request import urlopen, Request

url = "https://10fastfingers.com/typing-test/english"
# 补全标准浏览器请求头,模拟正常用户访问
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'
}
page = urlopen(Request(url, headers=headers)).read()
soup = BeautifulSoup(page, "lxml")

# 直接定位wordlist节点,无需额外匹配父级标签
wordlist_tag = soup.find("div", id='wordlist')
# 提取文本、去除首尾空白后按|分割,得到单词列表
word_list = wordlist_tag.text.strip().split('|')

# 打印前10个单词验证提取结果
print(word_list[:10])

# 可选:将所有单词逐行写入本地文件
with open("typing_word_list.txt", "w", encoding="utf-8") as f:
    f.write('\n'.join(word_list))
补充说明
  • 若需要提取德语、其他语言的测试单词,仅需替换代码中url为对应语言的测试页地址,提取逻辑完全一致
  • 如果运行后提取结果为空,先打开本地保存的page content.txt,搜索wordlist关键字确认源码中是否存在对应节点;如果节点不存在说明请求被反爬拦截,可尝试更新请求头、增加访问间隔后重试
  • 该单词列表直接存在于静态HTML源码中,无需使用Selenium等动态渲染工具即可提取,不需要执行页面JS

内容的提问来源于stack exchange,提问作者plex

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.30 17:27:22