【问题标题】:Python Web Scrape Write Output to FilePython Web Scrape 将输出写入文件
【发布时间】:2014-09-11 13:01:10
【问题描述】:

我有一个基本的 Python 脚本,可以将输出存储到文件中。这是一个很难解析的文件。 有没有其他方法可以将抓取的数据写入可以轻松读取到 Python 中进行分析的文件?

import requests
from bs4 import BeautifulSoup as BS
import json
data='C:/test.json'
url="http://sfbay.craigslist.org/search/sby/sss?sort=rel&query=baby" 

r=requests.get(url)
soup=BS(r.content)
links=soup.find_all("p")
#print soup.prettify()

for link in links:
    connections=link.text
    f=open(data,'a')
    f.write(json.dumps(connections,indent=1))
    f.close()

输出文件包含以下内容: “ 9 月 5 日 25 美元 Porcelain Baby Deer 25 美元(森尼韦尔)图片家居用品 - 所有者提供”“ 9 月 5 日 7500 美元 GEORGE STECK BABY GRAND PLAYER PIANO 7500 美元(摩根山)地图乐器 - 由

【问题讨论】:

    标签: python


    【解决方案1】:

    如果你想将它从 python 写入一个文件,然后再读回 python,你可以使用 Pickle - Pickle Tutorial

    Pickle 文件是二进制文件,人类无法阅读,如果这对您很重要,那么您可以查看 yaml,我承认它有一些学习曲线,但可以生成格式良好的文件。

    import yaml
    
    f = open(filename, 'w')
    f.write( yaml.dump(data) )
    f.close()
    
    ...
    
    
    stream = open(filename, 'r')
    data = yaml.load(stream)
    

    【讨论】:

    • 这将允许@Amrita Sawant 存储对象状态,但我认为它没有触及问题的核心,这是编写数据的好方法,因此它可以很容易地被以后用 Python。诚然,这个问题的范围有点宽泛。
    • 好点,我将“由 Python 解析”解释为“从文件中读取”,但您是对的,这可能不是问题的意图。在这种情况下,这是一个字符串操作问题,而不是文件 IO 问题。
    【解决方案2】:

    听起来您的问题更多是关于如何解析从 craigslist 获得的抓取数据,而不是如何处理文件。一种方法是获取每个<p> 元素并用空格标记字符串。例如,对字符串进行标记

    "$25 Sep 5 Porcelain Baby Deer $25 (sunnyvale) pic 家居用品 - 按所有者”

    可以使用split:

    s = " $25 Sep 5 Porcelain Baby Deer $25 (sunnyvale) pic household items - by owner "
    L = s.strip().split(' ') #remove whitespace at ends and break string apart by spaces
    

    L 现在是一个包含值的列表

    ['$25', 'Sep', '5', 'Porcelain', 'Baby', 'Deer', '$25', '(sunnyvale)', 'pic', 'household', 'items', '-', 'by', 'owner']
    

    从这里你可以尝试通过它们出现的顺序来确定列表元素的含义。 L[0] 可能始终持有价格,L[1] 月份,L[2] 月份日期,等等。如果您有兴趣将这些值写入文件并稍后再次解析,请考虑阅读csv module

    【讨论】:

      【解决方案3】:
      1. 确定您真正需要的数据。价格?说明?列出日期?
      2. 决定一个好的数据结构来保存这些信息。我推荐一个包含相关字段或列表的类。
      3. 使用正则表达式或许多其他方法之一抓取您需要的数据。
      4. 扔掉你不需要的东西

      5a。将列表内容以您以后可以轻松使用的格式(XML、逗号分隔等)写入文件

      5b。按照上面Mike Ounsworth 的建议腌制对象。

      如果您还不习惯 XML 解析,只需为每个链接写一行,并用稍后可以用来拆分的字符分隔您想要的字段。例如:

      import re #I'm going to use regular expressions here
      
      link_content_matcher = re.compile("""\$(?P<price>[1-9]{1,4})\s+(?P<list_date>[A-Z]{1}[a-z]{2}\s+[0-9]{1,2})\s+(?P<description>.*)\((?P<location>.*)\)""")
      
      some_link = "$50    Sep 5 Baby Carrier - Black/Silver (san jose)"
      
      # Grab the matches
      matched_fields = link_content_matcher.search(some_link)
      
      # Write what you want to a file using a delimiter that 
      # probably won't exist in the description. This is risky,
      # but will do in a pinch.
      output_file = open('results.txt', 'w')
      output_file.write("{price}^{date}^{desc}^{location}\n".format(price=matched_fields.group('price'),
          date=matched_fields.group('list_date'),
          desc=matched_fields.group('description'),
          location=matched_fields.group('location')))
      output_file.close()
      

      当你想重新访问这些数据时,从文件中逐行抓取并使用 split 解析。

      input_contents = open('results.txt', 'r').readlines()
      
      for line in input_contents:
          price, date, desc, location = line.split('^')
          # Do something with this data or add it to a list
      

      【讨论】:

        【解决方案4】:
        import requests
        from bs4 import BeautifulSoup as bs
        url="http://sfbay.craigslist.org/baa/"
        r=requests.get(url)
        soup=bs(r.content)
        import re
        s=soup.find_all('a', class_=re.compile("hdrlnk")) 
        for i in s:
          col=i.text
          scol=str(col)
          print scol
        
        s1=soup.find_all('span', class_=re.compile("price")) ### Price
        

        【讨论】:

          猜你喜欢
          • 2013-11-23
          • 1970-01-01
          • 1970-01-01
          • 2016-03-18
          • 2019-10-12
          • 1970-01-01
          • 2016-05-03
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多