![](/img/trans.png)
[英]How to get variable value from Javascript using Selenium with Python
[英]Error when extracting a JavaScript value from a variable with Selenium python
我正在尝试使用 Selenium webdriver 在 python 中获取该网站上变量remainingTimeString
时间字符串的值。 我正在尝试使用driver.execute_script()
function。 这是我的代码:
import selenium.webdriver
options = selenium.webdriver.FirefoxOptions()
options.add_argument("--headless")
driver = selenium.webdriver.Firefox(options=options)
driver.get('https://shopgoodwill.com/item/151632327')
print(driver.execute_script("return remainingTimeString"))
但是,当我运行它时,我得到:
selenium.common.exceptions.JavascriptException: Message: ReferenceError: remainingTimeString is not defined
我应该怎么办? 当我检查 HTML 源时,该变量显然在脚本中。 谢谢!
该数据是在页面加载后从 API 动态提取的,因此您的选择是 - 为该元素使用 WebDriverWait(或隐式等待),或使用不太复杂的解决方案,如下所示(无硒),在开发工具中检查网络选项卡的位置,找到从中提取数据的 API,然后直接刮取 API:
import requests
import pandas as pd
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36"
}
url = 'https://buyerapi.shopgoodwill.com/api/ItemDetail/GetItemDetailModelByItemId/151632327'
r = requests.get(url, headers=headers)
df = pd.json_normalize(r.json())
print(df['remainingTime'][0])
终端打印的结果:
'17h 56m '
上面的代码仅从 dataframe 中提取剩余时间。 json 中有详细的产品信息,如果需要,您也可以获取其他数据。 Python 请求文档可以在https://requests.readthedocs.io/en/latest/找到
还有 pandas 文档: https://pandas.pydata.org/pandas-docs/stable/index.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.