javascript - 使用 Python Selenium 在几秒后隐藏的元素上抓取 Javascript React 页面

标签 javascript python selenium web-scraping beautifulsoup

我正在尝试抓取一个具有 React 元素的网页,该元素会在几秒钟后隐藏下拉列表。

这是您第一次访问页面和我想要抓取的选项卡时看到的内容。

Dropdown element I want to scrape. Specifically the '24' people are viewing this event line.

我正在尝试抓取“不要错过!”的部分。 24 人正在观看此事件

几秒钟后,该选项卡消失并被另一个下拉元素取代,该元素显示以正确的价格获得通知!

new dropdown that replaces the one i want to scrape. It hides the previous dropdown

源代码显示观看次数下拉列表在几秒钟后隐藏。代码的顶部显示了新的下拉列表,而底部的 div 类中的 'hide' 是我想要抓取的下拉列表。

The source code showing the hidden dropdown code

我尝试获取 div class = "urgency-component-container 但由于它被隐藏,所以它什么也没有返回。我也尝试获取 div class = "dropdown-header-item" 但这也没有返回任何内容。

我尝试获取 dropdown-header-item 的 XPath (//*[@id="dropdown-header"]/div/div 1 ),但这也不起作用。

如何抓取几秒钟后“隐藏”的下拉菜单?谢谢

编辑:

网站网址是: https://www.stubhub.com/anaheim-ducks-tickets-anaheim-ducks-anaheim-honda-center-11-14-2019/event/104217448/?sort=price%20asc

我使用的代码是

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time

driver = webdriver.Chrome()
url = 'https://www.stubhub.com/anaheim-ducks-tickets-anaheim-ducks-anaheim-honda-center-11-14-2019/event/104217448/?sort=price+asc'
driver.get(url)

content = driver.find_element_by_class_name('dropdown-header-item')

如果我立即执行代码,则会收到错误

NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":".dropdown-header-item"}

但是如果我等待几秒钟并运行它,那么我会得到

Get notified at the right price!Set price alert

最佳答案

请尝试一下并让我知道效果如何。

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time

driver = webdriver.Chrome('/usr/local/bin/chromedriver')  # Optional argument, if not specified will search path.
driver.delete_all_cookies()
driver.implicitly_wait(15)
driver.maximize_window()
url = 'https://www.stubhub.com/anaheim-ducks-tickets-anaheim-ducks-anaheim-honda-center-11-14-2019/event/104217448/?sort=price+asc'
driver.get(url)
driver.refresh()

content = driver.find_element_by_xpath("//div[@class='urgency-wrapper']//div[@class='dropdown-header-item']").text
print content

driver.quit()

输出:

Don't miss out. 28 people are viewing this event.

关于javascript - 使用 Python Selenium 在几秒后隐藏的元素上抓取 Javascript React 页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58292563/

相关文章:

javascript - firebase中如何区分新旧元素?

javascript - Sequelize : Eager Loading and Ordering (on parent table)

python - 有没有办法将二进制文件(例如 chromedriver)与使用 Pyinstaller 编译的单个文件 app/exe 捆绑在一起?

python - 下载 PDF 作为文件对象,无需使用 Python 中的 Chrome 和 Selenium 下载文件

javascript - “webrtc_android”在构建时发出错误消息

javascript - 无法以编程方式更改 react 路由器中的路线

python - 将伪代码转换为 Python

python - 根据 channel 将输入图像张量切片或分割为变量

Python 正则表达式 : Finding input not matching a specific (variable-defined) length

ruby - 通过 xvfb-run 运行 selenium ruby​​ 脚本时出错