在一个变量中存储forloop输出

2024-09-29 06:27:07 发布

您现在位置:Python中文网/ 问答频道 /正文

当我运行我的代码时,我得到我在url中定义的酒店的价格,然后我得到所有其他酒店的价格作为建议。为了子集化和选择第一个输出,我需要将for循环输出存储在单个变量中或作为列表。我该怎么做?在

我使用的是python3.6.5,windows7professional

from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
chrome_path= r"C:\Users\Downloads\chromedriver_win32\chromedriver.exe"
  dr = webdriver.Chrome(chrome_path)
  dr.get("url")
 hoteltrial = dr.find_elements_by_class_name("hotel-info")

for hoteltrial1 in hoteltrial:
  nametrial = hoteltrial1.find_element_by_class_name("hotel-name")
  print(nametrial.text + " - ")
try:
    pricetrial = hoteltrial1.find_element_by_class_name("c-price")
    price = pricetrial.find_element_by_css_selector("span.price-num")
    currency = pricetrial.find_element_by_class_name("price-currency")
    print(currency.text + price.text)

except NoSuchElementException:
    print("sold")

实际产量看起来有点像这样,我只需要兰厄姆的价格

^{pr2}$

Tags: textnameurlby价格elementfind酒店
1条回答
网友
1楼 · 发布于 2024-09-29 06:27:07

您要做的是重写for循环中使用的变量。为循环中找到的每个新变量赋值。在

for i in range(5):
    x = i

运行此示例并查看for循环后分配给x的值,您将看到该值为4。你在你的代码中也是这样做的。在

要解决这个问题,可以在for循环之外定义一个列表,并将结果附加到此列表中。在

^{pr2}$

运行上述代码后,您将看到这将生成一个列表。在

hotel
[0,1,2,3,4]

你应该在你的代码中做同样的事情。在

hotellist = []
for hoteltrial1 in hoteltrial:
    nametrial = hoteltrial1.find_element_by_class_name("hotel-name")
    hName = nametrial.text + " - "
    try:
        pricetrial = hoteltrial1.find_element_by_class_name("c-price")
        price = pricetrial.find_element_by_css_selector("span.price-num")
        currency = pricetrial.find_element_by_class_name("price-currency")
        result = hName + currency.text + price.text
        hotellist.append(result)
    except NoSuchElementException:
        result = hName + "Sold"
        hotellist.append(result)

在运行这个for循环之后,您将得到一个列表,其中包含在循环的每次迭代中找到的所有结果。你可以用字典代替,这样你就可以通过搜索关键字得到每家酒店和价格。在

使用dict:

hoteldict = {}
for hoteltrial1 in hoteltrial:
    nametrial = hoteltrial1.find_element_by_class_name("hotel-name")
    try:
        pricetrial = hoteltrial1.find_element_by_class_name("c-price")
        price = pricetrial.find_element_by_css_selector("span.price-num")
        currency = pricetrial.find_element_by_class_name("price-currency")
        hoteldict.update({nametrial.text:currency.text+price.text})
    except NoSuchElementException:
        hoteldict.update({nametrial.text:"Sold"})

对于dictionary,使用update而不是append。在

访问您的酒店:

hoteldict["The Langham Hong Kong"] #Will return $272

我希望这对你有帮助。 谨致问候, 山姆

相关问题 更多 >