【问题标题】:Collect information from many elements with identic class (Selenium, Python)从具有相同类(Selenium、Python)的许多元素中收集信息
【发布时间】:2017-07-28 15:58:53
【问题描述】:

我正在尝试从 ebay 上收集商品的名称和价格。例如,我搜索了“armani”,而不是我需要使用 Selenium 收集第一页上的每个项目并将其附加到列表中。但我的代码有问题:

mylist = list()
for a in driver.find_element_by_xpath(".//*[@id='item3aeba8d9f0']/div"):
    name = a.findElement(By.xpath(".//*[@id='item3aeba8d9f0']/div/div[2]/h3]")).getText()
    price = a.findElement(By.xpath(".//*[@id='item3aeba8d9f0']/div/div[3]/div[2]/div/span[1]/span")).getText()
    mylist.append(name, price)
print(name)

结果应该是:[[name, price],[name, price],...]

【问题讨论】:

  • 什么是“我的代码中的问题”?问题应该是具体的......错误消息或问题描述。请阅读How to Ask,尤其是关于minimal reproducible example(MCVE)和How much research effort is expected?的部分,这将帮助您调试自己的程序并自己解决问题。如果您这样做但仍然卡住,您可以返回并发布您的 MCVE、您尝试过的内容以及执行结果(包括任何错误消息),以便我们更好地为您提供帮助。

标签: python selenium


【解决方案1】:

听起来您想将元组附加到表单列表(名称,价格)。 此外,当您想要遍历 Web 元素的集合时,您正在尝试遍历单个 Web 元素。

mylist = list()
for a in driver.find_elements_by_xpath(".//*[@id='item3aeba8d9f0']/div"): ##Change to .find_elements from .find_element
    name = a.findElement(By.xpath(".//*[@id='item3aeba8d9f0']/div/div[2]/h3]")).getText()
    price = a.findElement(By.xpath(".//*[@id='item3aeba8d9f0']/div/div[3]/div[2]/div/span[1]/span")).getText()
    mylist.append((name, price)) // THE CHANGE IS HERE!!!
    ##or you instead of tuples you could do a two element list.
    mylist.append([name, price]) // THE CHANGE IS HERE!!!
print(name)

【讨论】:

  • 问题出在for循环中。
  • @NurislomTuraev 尝试将driver.find_element_by_xpath("...") 更改为driver.find_elements_by_xpath("...")
猜你喜欢
  • 2017-07-21
  • 2020-05-23
  • 1970-01-01
  • 2014-07-18
  • 1970-01-01
  • 2015-10-04
  • 2014-09-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多