使用Selenium在网页上获取隐藏的产品详细信息

2024-10-02 18:26:22 发布

您现在位置:Python中文网/ 问答频道 /正文

很抱歉,我是一个硒菜鸟,读了很多书,但仍然无法从该页获取产品价格(0.55英镑): https://groceries.asda.com/product/spaghetti-tagliatelle/asda-spaghetti/36628。使用bs4解析html时,产品详细信息不可见。使用Selenium,我可以得到整个页面的一个字符串,并且可以看到其中的价格(使用以下代码)。我应该可以从中提取价格不知何故,但更喜欢一个不那么老套的解决方案。在

browser = webdriver.Firefox(executable_path=r'C:\Users\Paul\geckodriver.exe')
browser.get('https://groceries.asda.com/product/tinned-tomatoes/asda-smart-price-chopped-tomatoes-in-tomato-juice/19560')
content = browser.page_source

如果我运行这样的程序:

^{pr2}$

它只返回:selenium.webdriver.firefox.webelement.FirefoxWebElement(session=“df23fae6-e99c-403c-a992-a1adf1cb8010”,element=“6d9aac0b-2e98-4bb5-b8af-fcbe443af906”)

price是与此元素相关联的文本:p^{cl1}$


Tags: httpsbrowsercom价格productpricewebdrivertomatoes
2条回答

试试这个解决方案,它与硒和美容素一起使用

from bs4 import BeautifulSoup
from selenium import webdriver

url='https://groceries.asda.com/product/spaghetti-tagliatelle/asda-spaghetti/36628'

driver = webdriver.PhantomJS()
driver.get(url)

data = driver.page_source

soup = BeautifulSoup(data, 'html.parser')

ele = soup.find('span',{'class':'prod-price-inner'})

print ele.text

driver.quit()

它将打印:

^{pr2}$

elem的类型是WebElement。如果需要提取web元素的文本值,可以使用以下代码:

elem = driver.find_element_by_class_name("prod-price-inner")
print(elem.text)

相关问题 更多 >