一、准备工作

1、安装 Python,本文以 Python3.7.4 为例;

2、安装 Python 爬虫所需要的第三方库,本文以 requests 和 BeautifulSoup4 为例;

3、搜索食品商务网蔬菜价格数据的网址,本文以 http://www.foods.com.cn/price/price-list-2.html 为例。

二、编写爬虫程序

1、引入需要的第三方库:

import requestsfrom bs4 import BeautifulSoup
Python

2、设置请求头:

headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36'}
Python

3、发送请求:

url = 'http://www.foods.com.cn/price/price-list-2.html'response = requests.get(url, headers=headers)
Python

4、使用 BeautifulSoup 解析网页:

soup = BeautifulSoup(response.text, 'lxml')
Python

5、获取蔬菜价格数据:

price_list = soup.select('div.table_list table tr')
Python

6、将蔬菜价格数据存储到本地:

with open('price.txt', 'w', encoding='utf-8') as f:for item in price_list:item_list = item.get_text().split()f.write(' '.join(item_list) + '\n')
Python

三、结果展示

上述步骤完成后,便可以在本地生成一个 price.txt 的文件,里面存放的就是食品商务网蔬菜价格数据。