【问题标题】:How to save my scraped data in AWS s3 bucket如何将我抓取的数据保存在 AWS s3 存储桶中
【发布时间】:2020-06-22 20:47:36
【问题描述】:

How to integrate my scrapping code with lambda_handler to save the data in s3 bucket。我无法保存数据 我有 aws 帐户而不是企业帐户,由 aws fot 2.00 提供。需要将数据保存在 s3 存储桶中。存储桶名称为“my_bucket”。我能够生成 data.json 文件。如何使用 AWS 中的 lambda 处理程序将此 data.json 直接保存到 my_content 存储桶。

我的抓取代码如下

from bs4 import BeautifulSoup
import ssl
import json
import ast
import json
import os
from urllib.request import Request, urlopen
# For ignoring SSL certificate errors
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
def get_soup(url):
    req = Request(url, headers={'User-Agent': 'Mozilla/5.0'})
    webpage = urlopen(req).read()
    soup = BeautifulSoup(webpage, 'html.parser')
    return soup
url = 'https://www.youtube.com/feed/trending'
soup=get_soup(url)
html = soup.prettify('utf-8')
video_details = {}

#All the trending youtube links
youtubelinks = []
for a in soup.select('a[href^="/watch?v="]')[:3]:
    youtubelinks.append("https://www.youtube.com"+ a['href'])
    youtubelink = list(dict.fromkeys(youtubelinks))

for link in youtubelink:
    link=get_soup(link)
    for span in link.findAll('span',attrs={'class': 'watch-title'}):
        video_details['TITLE'] = span.text.strip()
    print(video_details)
    with open('data.json', 'w', encoding='utf8') as outfile:
        json.dump(video_details, outfile, ensure_ascii=False,indent=4)

AWS,我也写了代码放入 s3 存储桶。如何在两者之间进行整合

import boto3   
import tempfile
def lambda_handler(event, context):
    bucket_name = "my_content"
    file_name = "data.json"
    lambda_path = "/tmp/" + file_name
    s3_path = "/100001/20191010/" + file_name    
    s3 = boto3.client('s3', aws_access_key_id = access_key, aws_secret_access_key = secret_key, region_name = region)
    data_bin = open(file_name,'r')
    data = data_bin.read()
    s3.Bucket(bucket_name).put_object(Key=s3_path, Body=data)
    #temp = tempfile.TemporaryFile()
    #s3.put_object(temp, Bucket = 'my_content', Key = 'data.json')
    #temp.close()

【问题讨论】:

  • 旁注:请注意,没有“aws 免费帐户”之类的东西。相反,Free Usage Tier 是一种账单折扣,在 AWS 账户的前 12 个月内免费提供一定数量的服务。如果服务的使用超出规定的金额,将按正常收费。您收到账单折扣这一事实不会影响所使用服务的行为。
  • 免费帐户在某种意义上不是企业帐户。给 2.00 的帐户

标签: python amazon-s3 web-scraping


【解决方案1】:

以下是如何将数据(json 文件)保存到 S3:

  1. 确保附加到 Lambda 的 AWS IAM 角色具有访问您尝试上传文件的 S3 存储桶的写入权限。
  2. 抓取数据,写入文件并将其存储在/tmp 文件夹中。
  3. 使用 Boto 3 的 S3 客户端 put_object 函数从 /tmp 目录上传文件。

【讨论】:

    【解决方案2】:

    我已经写了一个完整的示例:

    创建一个桶:

    import boto3
    
    s3 = boto3.resource('s3')
    
    # create a bucket
    myBucket = 'stackoverflow2'
    
    try:
        s3.create_bucket(Bucket=myBucket, CreateBucketConfiguration={"LocationConstraint": "eu-central-1"})
    except:
        pass
    

    列出所有存储桶:

    # Retrieve the list of existing buckets
    s3 = boto3.client('s3')
    
    # list all buckets
    response = s3.list_buckets()
    
    # Output the bucket names
    print()
    print('Existing buckets:')
    for bucket in response['Buckets']:
        print(f'  {bucket["Name"]}')
    

    上传文件:

    # Upload a file
    print()
    filename = 'stackoverflow.json'
    with open(filename, 'r') as line:
        print(line.read())
    
    # Uploads the given file using a managed uploader, which will split up large
    # files automatically and upload parts in parallel.
    s3.upload_file(filename, myBucket, filename)
    

    列出桶的内容:

    #liste content
    for key in s3.list_objects(Bucket=myBucket)['Contents']:
        print(key['Key']) 
    

    输出:

    Existing buckets:
      stackoverflow2
      terra-form-serverless
    
    {"test": {
      "id": "1",
      "value": "2",
      "attribute": {
        "sub": [
          {"value": "1", "2": "3"},
          {"value": "4", "5": "6"},
          {"value": "7", "8": "9"}
        ]
      }
    }}
    
    stackoverflow.json
    

    【讨论】:

      猜你喜欢
      • 2022-12-20
      • 2021-07-23
      • 2016-03-02
      • 1970-01-01
      • 2012-01-05
      • 1970-01-01
      • 1970-01-01
      • 2019-08-06
      • 2020-07-29
      相关资源
      最近更新 更多