
关注让阿豪来帮你解答,本回答参考chatgpt3.5编写提供,如果还有疑问可以评论或留言问题:如何使用Python爬取网页上的数据并存储到本地? 回答: 一、准备工作 1.安装Python环境 2.安装requests库和beautifulsoup4库(可使用pip安装)
pip install requests
pip install beautifulsoup4
二、爬取数据 1.使用requests库向网页发送请求,获取响应
import requests
url = 'https://www.example.com'
response = requests.get(url)
2.使用beautifulsoup4库解析网页内容,获取目标数据
from bs4 import BeautifulSoup
soup = BeautifulSoup(response.text, 'html.parser')
data = soup.find('div', class_='data').text
以上代码中,使用了beautifulsoup4库的.find()方法定位到网页中class属性为"data"的div元素,再用.text将其内容存储到data变量中。 三、存储数据 1.使用Python内置的open()函数打开一个文件
with open('data.txt', 'w') as f:
f.write(data)
以上代码中,使用了with语句打开文件,其中的'w'表示写入模式,如果文件不存在则会创建一个新文件。 2.存储为CSV格式
import csv
with open('data.csv', 'w', newline='') as f:
writer = csv.writer(f)
writer.writerows(data)
以上代码使用了Python标准库中的csv模块,将数据写入到以.csv结尾的文件中。 案例: 下面以豆瓣电影为例,爬取电影名称和评分,并将其保存为CSV文件。
import requests
from bs4 import BeautifulSoup
import csv
url = 'https://movie.douban.com/top250'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
movies = soup.find_all('div', class_='hd')
data = []
for movie in movies:
title = movie.a.span.text
rating = movie.parent.find('span', class_='rating_num').text
data.append([title, rating])
with open('movies.csv', 'w', newline='', encoding='utf-8') as f:
writer = csv.writer(f)
writer.writerows(data)
以上代码首先定位到class属性为"hd"的div元素,然后使用.text方法获取电影名称和评分,最后将其保存为CSV文件。如果需要保存为其他格式的文件,可以使用不同的模块进行处理。