如何从Wordle获取html

问题描述 投票:0回答:1

我尝试使用 Beautiful Soup 来抓取 Wordle,但它没有按预期工作(很可能是因为它是 JavaScript 动态的)。我试着环顾四周,发现我必须使用 Selenium 才能抓取页面。我尝试了 Selenium,它似乎工作得更好,但它没有我需要的 HTML 元素。

from pathlib import Path
import requests
from bs4 import BeautifulSoup
import time
from selenium import webdriver
url = 'https://www.nytimes.com/games/wordle/index.html'
driver = webdriver.Firefox()
driver.get(url)

#this will not work 
#driver.find_element_by_class_name('Keyboard-module_keyboard__uYuqf')

pageSource = driver.page_source
f = open(Path.cwd()/ 'dfkdf.txt', 'w')
f.write(pageSource)
f.close()

FE:当我尝试查找“Keyboard-module_keyboard__uYuqf”类时,它不会返回任何内容。

我问了 ChatGPT,查了很多资料,现在已经被这个问题困扰了几天了。我怎样才能做到这一点?

python selenium-webdriver web-scraping beautifulsoup
1个回答
0
投票

很难从你的问题中判断出到底是什么目标,但你提到了一个特定的定位器,所以我编写了一个简短的脚本来演示如何使用该定位器并返回该定位器包含的键盘上显示的所有键。

from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

url = "https://www.nytimes.com/games/wordle/index.html"
driver = webdriver.Chrome()
driver.maximize_window()
driver.get(url)

wait = WebDriverWait(driver, 10)
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button[data-testid='Play']"))).click()            # click Play
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "svg[data-testid='icon-close']"))).click()         # close the How to Play popup
keys = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, ".Keyboard-module_keyboard__uYuqf"))).text  # get the keys on the keyboard
print(keys)

然后打印出来

Q
W
E
R
T
Y
U
I
O
P
A
S
D
F
G
H
J
K
L
ENTER
Z
X
C
V
B
N
M

我不确定你要用它做什么......但它就在那里。

© www.soinside.com 2019 - 2024. All rights reserved.