【发布时间】: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