python - 卡在 for 循环中的第一个元素上
问题描述
我制作了一个脚本,可以搜索 Steam 市场。我正在使用 for 循环来检查不同的列表,但我只使用第一个元素时遇到问题,所以我只得到第一个列表。
这是我正在使用的代码:
driver = uc.Chrome()
driver.get('https://chrome.google.com/webstore/detail/csgofloat-market-checker/jjicbefpemnphinccgikpdaagjebbnhg/related?hl=en')
time.sleep(4)
driver.get('https://steamcommunity.com/market/listings/730/%E2%98%85%20Gut%20Knife%20%7C%20Case%20Hardened%20%28Factory%20New%29')
time.sleep(3)
articles = driver.find_elements_by_xpath('//span[starts-with(@id, "listing_")]')
time.sleep(3)
for article in articles:
print(article.text)
pris = article.find_element_by_xpath('//*[starts-with(@class, "market_listing_price market_listing_price_with_fee")]' and '//span[contains(@class, "market_listing_price market_listing_price_with_fee")]')
Float = article.find_element_by_xpath('//*[starts-with(@class, "csgofloat-itemseed")]')
print(pris.text)
print(Float.text)
当我运行它时,输出是:
★ Gut Knife | Case Hardened (Fabriksny)
747,50zł
Paint Seed: 981
★ Gut Knife | Case Hardened (Fabriksny)
747,50zł
Paint Seed: 981
★ Gut Knife | Case Hardened (Fabriksny)
747,50zł
Paint Seed: 981
解决方案
基本上 xpath '//*[starts-with(@class, "market_listing_price market_listing_price_with_fee")]' and '//span[contains(@class, "market_listing_price market_listing_price_with_fee")]'
在语法上是错误的,正确的是'//*[starts-with(@class, "market_listing_price market_listing_price_with_fee") and contains(@class, "market_listing_price market_listing_price_with_fee")]'
或者更简单'//*[starts-with(@class, "market_listing_price market_listing_price_with_fee")]'
。此外,我无法'//*[starts-with(@class, "csgofloat-itemseed")]'
在页面中找到带有路径的元素。
除此之外,当您遍历元素时,您必须以点开头的路径才能访问给定元素的子元素,我认为这是您的问题。因此,您可以执行以下操作:
articles_box = driver.find_elements_by_xpath("//div[starts-with(@class, 'market_listing_row market_recent_listing_row')]")
for a in articles_box:
article = a.find_element_by_xpath('.//span[starts-with(@id, "listing_")]')
print(article.text)
pris = a.find_element_by_xpath('.//*[starts-with(@class, "market_listing_price market_listing_price_with_fee")]')
Float = a.find_element_by_xpath('.//*[starts-with(@class, "csgofloat-itemseed")]')
print(pris.text)
print(Float.text)
(我真的建议你使用WebDriverWait
而不是那个时间睡觉)
推荐阅读
- python - 如何确保“email.FeedParser”模块的存在
- c# - 使用类的相同对象,但成员不同
- optimization - 需要帮助理解 PySpark 解释输出
- node.js - 尝试使用 NPM 包但始终找不到“fs”
- freepascal - freepascal 中的 PascalScript
- c# - Visual Studio 项目安装
- javascript - Highcharts spiderweb - 如何在空数据的情况下修复 xAxis 间隔
- python - scikit-learn & statsmodels - 哪个 R 平方是正确的?
- css - 无法在 Cloud 9 ide 中使用 react 来定位 css 类
- jquery - 将 jQuery 序列化 URL 转换为 JSON 对象