【问题标题】:Python crawling JSON - Getting all items backPython 抓取 JSON - 取回所有项目
【发布时间】:2017-09-12 03:58:27
【问题描述】:

我目前面临的问题是我无法从特定网站上抓取我想要的信息。

详细来说,我想获取 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 €

正如你们所看到的,价格显示正确,但项目(标题)没有不同。我只是拿回一件特定的物品。

你们能帮帮我吗?任何反馈表示赞赏。

【问题讨论】:

    标签: python json beautifulsoup request web-crawler


    【解决方案1】:
    for titles in header:
        title_final = (titles.get("title"))
    

    这段代码运行,在它的最后,title_final 有一个值,代码继续下一个。 Python 不会神奇地跟踪分配给变量的所有值,然后将不同的 for 循环链接在一起。您需要在一个循环中完成所有操作,或者将数据存储在列表中并将它们与zip 或其他东西结合起来。

    for item in js_dict:
    

    您没有使用item。您只是从循环内的字典中直接获取内容:

    (js_dict['searchResults']["tours"])
    

    你重复了三遍,所以header == url == price

    停下来想想你的代码。到处放print 语句,看看发生了什么以及变量的值是什么。

    【讨论】:

      【解决方案2】:

      您的 for 循环不正确。对于每个prices in price,您将只有 1 个(最后一个)title_final,因此会出现问题。

      你可能想做-

      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)
      

      【讨论】:

      • 感谢您的帮助。欣赏它。但是现在我收到以下价格错误:price_final = prices.get("price")["original"] AttributeError: 'list' object has no attribute 'get' 你对此有什么建议吗?抱歉,我是 python 新手
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-08-17
      • 1970-01-01
      • 2021-10-13
      • 2018-06-09
      • 2021-10-20
      • 2011-11-20
      • 2018-09-22
      相关资源
      最近更新 更多