我试图从THIS WEBSITE中获取一些产品有3种价格的数据(静音价格、红色价格和黑色价格),我观察到,当产品有3种价格时,红色价格在页面加载前发生变化。在
当我刮网站我只得到两个价格,我想如果代码等到页面完全加载我会得到所有的价格。在
这是我的代码:
url='https://www.exito.com/televisor-led-samsung-55-pulgadas-uhd-4k-smart-tv-serie-7-24449/p'
req = requests.get(url)
soup = BeautifulSoup(req.text, "lxml")
# Muted Price
MutedPrice = soup.find_all("span",{'class':'exito-vtex-components-2-x-listPriceValue ph2 dib strike custom-list-price fw5 exito-vtex-component-precio-tachado'})[0].text
MutedPrice=pd.to_numeric(MutedPrice[2-len(MutedPrice):].replace('.',''))
# Red Price
RedPrice = soup.find_all("span",{'class':'exito-vtex-components-2-x-sellingPrice fw1 f3 custom-selling-price dib ph2 exito-vtex-component-precio-rojo'})[0].text
RedPrice=pd.to_numeric(RedPrice[2-len(RedPrice):].replace('.',''))
# black Price
BlackPrice = soup.find_all("span",{'class':'exito-vtex-components-2-x-alliedPrice fw1 f3 custom-selling-price dib ph2 exito-vtex-component-precio-negro'})[0].text
BlackPrice=pd.to_numeric(BlackPrice[2-len(BlackPrice):].replace('.',''))
print('Muted Price:',MutedPrice)
print('Red Price:',RedPrice)
print('Black Price:',BlackPrice)
实际结果: 静音价格:319.99万 红色价格:1649868 黑色价格:0
预期结果: 静音价格:319.99万 红色价格:1550032 黑价:1649868
这些值可能是动态呈现的,也就是说,这些值可能由页面中的javascript填充。在
requests.get()
只返回从服务器接收到的标记,而不做任何进一步的客户端更改,因此它不是完全关于等待。在您可以使用Selenium Chrome Webdriver加载页面URL并获取页面源代码。(或者您可以使用Firefox驱动程序)。在
转到
chrome://settings/help
检查您当前的chrome版本并从here下载该版本的驱动程序。请确保将驱动程序文件保存在PATH
或python脚本所在的同一文件夹中。在尝试将现有代码的前3行替换为:
输出:
^{pr2}$参考文献:
Get page generated with Javascript in Python
selenium - chromedriver executable needs to be in PATH
您尝试抓取的页面包含JavaScript代码,该代码由浏览器执行,并在下载后修改页面。如果要对页面的“最终状态”执行提取,则需要使用专用于该状态的库在页面上运行JavaScript代码。不幸的是,beauthoulsoup没有这个功能,您需要使用另一个库来完成您的任务。在
例如,您可以
pip install requests-html
并运行以下命令:它打印以下内容:
^{pr2}$相关问题 更多 >
编程相关推荐