【问题标题】:Web scraping - filtering results网页抓取 - 过滤结果
【发布时间】:2015-02-19 16:13:02
【问题描述】:

所以我是 python 新手,对网络抓取非常陌生,可以使用一些帮助。即使我真的理解这种语言,我还是设法拼凑(忽略了双关语)一些东西。我正在尝试从某些 Steam 市场商品中获取价格,这就是我目前所拥有的:

import urllib.request
import re

urls = ["http://steamcommunity.com/market/listings/730/AK-47%20%7C%20Redline%20%28Field-Tested%29"]
i=0
pattern = re.compile(b'<span class="market_listing_price market_listing_price_with_fee">\s+(.+?)\s+</span>')

while i< len(urls):
    htmlfile = urllib.request.urlopen(urls[i])
    htmltext = htmlfile.read()
    titles = re.findall (pattern,htmltext)

    print (titles)
    i+=1

这给出了这样的结果:

[b'471,50 p&#1091;&#1073;.', b'CDN&#36; 9.50', b'Rp 103 500.99', b'&#36;8.39 USD', b'&#36;8.40 USD', b'499,99 p&#1091;&#1073;.', b'499,99 p&#1091;&#1073;.', b'6,90&#8364;', b'6,90&#8364;', b'6,90&#8364;']

如您所见,这对眼睛来说根本不是很友好,我想要得到的只是最便宜商品的价格(仅美元)(在这种情况下:b'&amp;#36;8.39 USD')。我如何过滤结果,以便它只给我列表中的最低价格,如下所示:8.39 USD

正如我之前所说,我对 python 和网络抓取非常陌生,因此可能需要更多代码方面的帮助。

【问题讨论】:

    标签: python python-3.x web web-scraping screen-scraping


    【解决方案1】:

    使用 HTML 解析器,例如 BeautifulSoup

    我们的想法是遍历结果(div,id 为searchResultsRows)并获取所有span 类为market_listing_price 的元素。然后,对于每个span,使用正则表达式提取价格:

    import re
    import urllib.request
    
    from bs4 import BeautifulSoup
    
    urls = ["http://steamcommunity.com/market/listings/730/AK-47%20%7C%20Redline%20%28Field-Tested%29"]
    
    pattern = re.compile(r'([0-9\.,]+)')
    for url in urls:
        soup = BeautifulSoup(urllib.request.urlopen(url))
    
        prices = []
        for price in soup.select('div#searchResultsRows span.market_listing_price'):
            match = pattern.search(price.text)
            if match:
                prices.append(float(match.group(1).replace(',', '.')))
    
        print(prices)
    

    打印:

    [6.26, 5.45, 458.0, 398.27, 57.5, 50.0, 8.0, 6.97, 8.12, 7.07, 6.8, 5.92, 499.99, 434.79, 6.87, 5.99, 502.97, 437.38, 6.9, 6.0]
    

    顺便说一句,您可能已经注意到没有单一的货币设置,每个价格都有自己的价格 - 这也是您需要考虑的。

    【讨论】:

      猜你喜欢
      • 2016-07-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-18
      相关资源
      最近更新 更多