【问题标题】:Scrape and return a value from within a div class with Python使用 Python 从 div 类中抓取并返回一个值
【发布时间】:2019-12-29 13:54:13
【问题描述】:

知道如何从这个源代码视图中检索价格(现在是 2917.99)-https://www.emag.ro/televizor-led-smart-samsung-138-cm-55ru7402-4k-ultra-hd-ue55ru7402uxxh/pd/DTN2XZBBM/

如果我调用类 p.product-new-price 我得到 None。

我设法得到了标题,但没有得到价格。

到目前为止我做了什么:

import requests

from bs4 import BeautifulSoup 

URL = 'https://www.emag.ro/televizor-led-smart-samsung-138-cm-55ru7402-4k-ultra-hd-ue55ru7402uxxh/pd/DTN2XZBBM/'

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

page = requests.get(URL, headers = headers)

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

title = soup.find('title')

div = soup.find('div', {"class" : 'product-new-price'})

text = div.string

print(text)

该类如下所示,我想将 2917 提取为 int。

div class="product-highlight product-page-pricing"    
            p class="product-new-price"
       2.917<sup>99</sup> <span>Lei</span>

非常感谢!

【问题讨论】:

    标签: python html web-scraping


    【解决方案1】:

    好的,稍作修改:

    • 对我来说,product-new-price 类似乎在 p 元素上!
    • 我假设在主要价格之后总会有一个&lt;sup&gt; 标签
    import requests
    
    from bs4 import BeautifulSoup
    
    URL = 'https://www.emag.ro/televizor-led-smart-samsung-138-cm-55ru7402-4k-ultra-hd-ue55ru7402uxxh/pd/DTN2XZBBM/'
    headers = {"User-Agent":'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36'}
    page = requests.get(URL, headers = headers)
    soup = BeautifulSoup(page.content, 'html.parser')
    title = soup.find('title')
    
    p = soup.find('p', {"class" : 'product-new-price'})
    
    # Get the text before <sup> tag
    value = p.find('sup').previousSibling.strip()
    print("Value: {}".format(value))
    
    # Keep only numbers
    value = ''.join(c for c in value if c.isdigit())
    price = int(value)
    print("Price: {}".format(price))
    

    以上打印:

    $ python3 ./test.py
    Value: 2.917
    Price: 2917
    

    现在,如果需要,您还可以通过小改动添加缺少的 .99

    【讨论】:

    • @OviSele 如果它完成了工作,请随时接受它;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-14
    • 1970-01-01
    • 1970-01-01
    • 2019-07-01
    • 2014-01-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多