网页抓取:将数据写入文件
原文:https://www.studytonight.com/python/web-scraping/writing-scraped-data-to-file
在上一个教程中,我们成功地从一个网站获取了数据,并将数据打印在控制台上。
但是一般来说,当我们从任何网站收集(提取)这么多数据时,我们不只是想在控制台上打印它,而是想把它写到某个文件中,或者可能将它插入到数据库中。
在本教程中,我们将扩展上一个教程,并将从消费者报告网站获取的产品列表写入文件。
我们将使用 python 的csv
模块将数据写入 Excel CSV 格式。
将数据写入 CSV 文件
第一步是在我们开始使用之前将模块csv
导入到我们的代码中,
## importing csv module
import csv
如果您愿意,您可以创建一个名为 product_data.csv 的 csv 文件,我们将把提取的数据写入该文件,或者下面的代码也将创建一个文件:
## then we open a csv file in append mode
with open("product_data.csv", "a") as csv_file:
writer = csv.writer(csv_file)
## now we will write data to it,
## using writer.writerow() method
这就是完整代码的样子。我们提取数据的部分在之前的教程中有说明,之后我们添加了代码,将提取的数据写入 csv 文件:
## importing bs4, requests, fake_useragent and csv modules
import bs4
import requests
from fake_useragent import UserAgent
import csv
## initializing the UserAgent object
user_agent = UserAgent()
url = "https://www.consumerreports.org/cro/a-to-z-index/products/index.htm"
## getting the reponse from the page using get method of requests module
page = requests.get(url, headers={"user-agent": user_agent.chrome})
## storing the content of the page in a variable
html = page.content
## creating BeautifulSoup object
soup = bs4.BeautifulSoup(html, "html.parser")
## div tags with crux-body-copy class
div_class = "crux-body-copy"
## getting all the divs with class 'crux-body-copy'
div_tags = soup.find_all("div", class_="div_class")
## then we open a csv file in append mode
with open("product_data.csv", "a") as csv_file:
writer = csv.writer(csv_file)
## extracting the names and links from the div tags
for tag in div_tags:
name = tag.a.text.strip()
link = tag.a['href']
## now we will write data to the file
writer.writerow([name, link])
试着在你的机器上运行这段代码,如果你遇到任何问题,你可以在这里发布你的问题: StudyTonight Q & A 论坛