一、准备工作
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
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'}
3、发送请求:
url = 'http://www.foods.com.cn/price/price-list-2.html'response = requests.get(url, headers=headers)
4、使用BeautifulSoup解析网页:
soup = BeautifulSoup(response.text, 'lxml')
5、获取蔬菜价格数据:
price_list = soup.select('div.table_list table tr')
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')
三、结果展示
上述步骤完成后,便可以在本地生成一个price.txt的文件,里面存放的就是食品商务网蔬菜价格数据。