所以我对 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уб.', b'CDN$ 9.50', b'Rp 103 500.99', b'$8.39 USD', b'$8.40 USD', b'499,99 pуб.', b'499,99 pуб.', b'6,90€', b'6,90€', b'6,90€']
正如你所看到的,这对眼睛来说一点也不友好,我想要得到的只是最便宜的商品的价格(仅美元)(在本例中:b' 36;8.39 美元'
)。如何过滤结果,使其只给出列表中的最低价格,如下所示:8.39 USD
。
正如我之前所说,我对 python 和网络抓取非常陌生,因此可能需要更多关于代码的帮助。
最佳答案
使用 HTML 解析器,例如 BeautifulSoup
.
这个想法是迭代结果(id为searchResultsRows
的div
)并获取具有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/