我目前面临的问题是,我无法从一个伙伴网站上获取我想要的信息。
详细地说,我想得到所有的项目和价格的目击是在JSON。
到目前为止,我能够收回所有的价格,但没有得到所有的项目以及返回。我要拿回一件特别的东西。
不知道问题出在哪里。
到目前为止,这就是我的逻辑:
session = requests.Session()
session.cookies.get_dict()
url = 'http://www.citydis.com'
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}
response = session.get(url, headers=headers)
soup = BeautifulSoup(response.content, "html.parser")
metaConfig = soup.find("meta", property="configuration")
jsonUrl = "https://www.citydis.com/s/results.json?&q=London& customerSearch=1&page=0"
js_dict = (json.loads(response.content.decode('utf-8')))
for item in js_dict:
header = (js_dict['searchResults']["tours"])
for titles in header:
title_final = (titles.get("title"))
url = (js_dict['searchResults']["tours"])
for urls in url:
url_final = (urls.get("url"))
price = (js_dict['searchResults']["tours"])
for prices in price:
price_final = (prices.get("price")["original"])
print("Header: " + title_final + " | " + "Price: " + price_final)这就是输出:
Header: Ticket für Madame Tussauds London & Star-Wars-Erlebnis | Price: 83,66 €
Header: Ticket für Madame Tussauds London & Star-Wars-Erlebnis | Price: 37,71 €
Header: Ticket für Madame Tussauds London & Star-Wars-Erlebnis | Price: 152,01 €正如你们所看到的,价格是正确的显示,但项目(标题)并没有不同。我要拿回一件特别的东西。
你们能帮帮我吗?如有任何反馈,将不胜感激。
发布于 2017-04-16 10:30:50
您的for循环不正确。您的每个title_final都只有一个(最后一个) prices in price,因此出现了这个问题。
你可能想做-
for item in js_dict:
headers = js_dict['searchResults']["tours"]
prices = js_dict['searchResults']["tours"]
for title, price in zip(headers, prices):
title_final = titles.get("title")
price_final = prices.get("price")["original"]
print("Header: " + title_final + " | " + "Price: " + price_final)发布于 2017-04-16 10:31:13
for titles in header:
title_final = (titles.get("title"))这段代码运行,在它的末尾,title_final只有一个值,并且代码移到下一件事情上。Python不会神奇地跟踪分配给变量的所有值,然后将不同的循环链接到一起。您需要在一个循环中完成所有操作,或者将数据存储在列表中,并将它们与zip或其他东西组合起来。
for item in js_dict:您没有使用item。你只是直接从循环中的字典中得到了一些东西:
(js_dict['searchResults']["tours"])你重复了三遍,所以header == url == price。
停下来想想你的代码。到处放置print语句,查看发生了什么以及变量的值是什么。
https://stackoverflow.com/questions/43436137
复制相似问题