将for循环输出存储在一个变量中

时间:2019-01-15 10:20:58

标签: python for-loop web-scraping

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

我正在使用python 3.6.5,Windows 7 Professional

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")

实际输出看起来像这样,我只需要朗廷的价格

The Langham Hong Kong - 
$272
Cordis Hong Kong - 
$206
Island Shangri-La - 
$881

1 个答案:

答案 0 :(得分:1)

您正在执行的操作将覆盖您在for循环中使用的变量。对于每次迭代,都会将找到的新值分配给循环中的变量。

for i in range(5):
    x = i

运行此示例并查看在for循环后分配给x的值时,您会看到该值为4。您在代码中所做的相同。

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

hotel = []
for i in range(5):
    hotel.append(i)

运行上面的代码后,您将看到结果列表。

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循环后,您将获得一个列表,其中包含在循环的每次迭代中找到的所有结果。您可以改用字典,这样就可以通过搜索键来获取每个酒店和价格。

使用字典:

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"})

对于字典,请使用update而不是append。

访问您的hoteldict:

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

我希望这对您有所帮助。 亲切的问候, 山姆