Skip to main content
 首页 » 编程设计

python之网页抓取之过滤结果

2024年10月25日12softidea

所以我是 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 .

这个想法是迭代结果(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] 

附带说明一下,您可能已经注意到没有单一的货币集,每个价格都有自己的价格 - 这也是您需要考虑的。