Python 在一个变量中存储for循环输出
当我运行我的代码时,我会得到我在url中定义的酒店的价格,然后我会得到作为建议的所有其他酒店的价格。为了子集和选取第一个输出,我需要将for循环输出存储在单个变量或列表中。我该怎么做 我使用的是python 3.6.5和Windows7 professionalPython 在一个变量中存储for循环输出,python,for-loop,web-scraping,Python,For Loop,Web Scraping,当我运行我的代码时,我会得到我在url中定义的酒店的价格,然后我会得到作为建议的所有其他酒店的价格。为了子集和选取第一个输出,我需要将for循环输出存储在单个变量或列表中。我该怎么做 我使用的是python 3.6.5和Windows7 professional from selenium import webdriver from selenium.common.exceptions import NoSuchElementException chrome_path= r"C:\Users\D
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
您正在做的是重写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循环之后,您将拥有一个列表,其中包含在循环的每个迭代中找到的所有结果。你可以用字典来代替,这样你就可以通过搜索关键字来获得每家酒店和价格
使用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"})
对于字典,使用update而不是append
访问您的酒店:
hoteldict["The Langham Hong Kong"] #Will return $272
我希望这对你有帮助。
亲切问候,,
Sam您仍然要打印其余的还是只需要第一个值?只需要第一个值。