如何使用Selenium从动态网站中获取数据

2024-09-30 16:29:40 发布

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

我是硒新手,希望通过我的课程链接降低价格提供结束时间。我该怎么做

价格和课程结束时间将动态加载到网站。我知道如何从网站中提取简单内容,但不知道如何提取动态内容

我已尝试使用Parsel库+Seleminium库,但返回空字符串。因为当我在手机中查看source网站时,source中没有显示价格。但当我点击chrome或firefox的inspect元素选项时。价格在跨度标签内提供。表示在浏览器上呈现页面时,将动态加载价格。如何在Selenium中执行此操作

以下是我的课程链接示例:

https://www.udemy.com/course/data-science-deep-learning-in-python/


Tags: 字符串source内容网站链接时间动态价格
1条回答
网友
1楼 · 发布于 2024-09-30 16:29:40

在您的环境中已经安装了所有依赖项的情况下,此代码应该可以工作:

    from selenium import webdriver
    from bs4 import BeautifulSoup
    from webdriver_manager.chrome import ChromeDriverManager

    driver = webdriver.Chrome(ChromeDriverManager().install())
    driver.get("https://www.udemy.com/course/appium-selenium-for-mobile-automation-testing/")

    content = driver.page_source

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

    price = soup.find('div', {'class':'price-text price-part Tu6MH udlite-clp-discount-price udlite-heading-xl'})
    if price is not None:
        price.text.strip()
        price = price.replace('Current price','')
        print('Price: ' + price)
        
        offerEndTime = soup.find('span', {'data-purpose':'safely-set-inner-html:discount-expiration:expiration-text'}).text.strip()
        print('Offer end time: ' +  offerEndTime)
    else:
        print('This is a free course')

相关问题 更多 >