python - 网页抓取 - 过滤结果

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

所以我对 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'&# 36;8.39 美元')。如何过滤结果,使其只给出列表中的最低价格,如下所示:8.39 USD

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

最佳答案

使用 HTML 解析器,例如 BeautifulSoup .

这个想法是迭代结果(id为searchResultsRowsdiv)并获取具有market_listing_price类的所有span元素.然后,对于每个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]

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

关于python - 网页抓取 - 过滤结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27587838/

相关文章:

python - 如何访问应用程序 'File Description' ?

python - 在 Pandas 中折叠列和索引

javascript - 如何将 html Bootstrap 代码集成到 javascript 代码中?

python - python中的字段继承访问

python - 如何识别 Pandas 中仅包含元组的列?

python - login_required 编码下一个参数,重定向失败

node.js - 我通过 Node js 将 sqlite3 查询结果作为 json 发送到浏览器

python - 计算 DataFrame Pandas 中 'times' 行之间的差异

python-3.x - 在Jinja2中使用 “if any():”?

javascript - element.execCommand()中的aShowDefaultUI参数引用的 'the default user interface'是什么?