【问题标题】:Scape gtag/jquery variables with BeautifulSoup?Scape gtag/jquery 变量与 BeautifulSoup?
【发布时间】:2021-11-10 22:14:25
【问题描述】:

TL/DR - 如何从本文底部的代码中获取价格值? ('价格': '124.99', )

您好,我正在尝试创建一个 python scraper,我有以下教程中的代码:

import requests
from bs4 import BeautifulSoup

URL = ''

headers = {
"User-Agent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.63 Safari/537.36 Edg/93.0.961.44'}

page = requests.get(URL, headers=headers)
soup = BeautifulSoup(page.content, 'html.parser')
    
print(soup.prettify())

打印返回很多,但我尝试解析的变量如下所示:

 <!-- WooCommerce JavaScript -->   <script type="text/javascript">    jQuery(function($) {

                        $( '.single_add_to_cart_button' ).on( 'click', function() {  

.....跳过 50+ 行

                    $( '.products .post-4381 a' ).on('click', function() {
                            if ( true === $(this).hasClass( 'add_to_cart_button' ) ) {
                                    return;
                            }
                            gtag( 'event', 'select_content', {
                                    'content_type': 'product',
                                    'items': [ {
                                            'id': '4381',
                                            'name': 'Broad Spectrum',
                                            'category': 'Tanning Oil&amp; Isolates',    
                                         'list_position': '9'

                                    } ], y': 'Oil/&amp; ',
                                    'price': '124.99',
                            } ]
                    } );

如何从这里提取 price 值?这是此页面上唯一名为价格的东西

【问题讨论】:

标签: python beautifulsoup python-requests


【解决方案1】:

价格在class="price-wrapper"标签内:

import requests
from bs4 import BeautifulSoup

URL = "https://www.reefersbay.com/product/bulk-delta-8-oil-100-grams/"

headers = {
    "User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:92.0) Gecko/20100101 Firefox/92.0"
}

page = requests.get(URL, headers=headers)
soup = BeautifulSoup(page.content, "html.parser")

price = soup.select_one(".price-wrapper ins").text
print(price)

打印:

$124.99

如果您希望价格浮动:

print(float(price.replace("$", "")))

打印:

124.99

【讨论】:

  • 非常感谢!我会投票,但我还没有 15 声望。我对python很陌生,但我试图弄清楚这一点,但无法弄清楚。我想我现在明白了,它看起来像是在价格包装器 div 中寻找 ins 标记并删除其间的所有 html 内容。谢谢! select_one 只是从上到下抓取第一个吗?
猜你喜欢
  • 2020-04-16
  • 1970-01-01
  • 2012-07-03
  • 2021-07-20
  • 2017-09-07
  • 1970-01-01
  • 2015-01-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多