为了让大家去菜市场砍价的时候,心里更有底,我写了一个小程序,抓取新发地官网公布的农副产品价格,并存入数据库,仅供研究。
简单说一下思路吧:
- 从新发地官网找到数据展示的规律,发现不同的类别和页数,是通过两个接口参数控制的,因此将URL模板设计成动态的,带有两个动态参数。
- 例行获取页面的bs4实体,通过div标签和class属性,找到要获取的数据列表。
- 把数据过滤好,存入列表。第一行固定是标题,后面是数据。
- 把数据存入数据库。建表过程这里就省略了。
- 因为考虑到网站的数据量很庞大,我们也没有必要抓取全部,因此考虑增加一个起始时间,只抓取这个时间以后的数据。
- Round one, fight!
from bs4 import BeautifulSoup
import requests
import pymysql
HEADER = {
"User-Agent": "Mozilla/5.0 (Linux; Android 9; DUK-AL20) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.119 Mobile Safari/537.36",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
"Accept-Encoding": "gzip, deflate",
"Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8,zh-TW;q=0.7",
}
# URL模板,需要动态调整的主要是类别和页数两个字段
BASE_URL = 'http://www.xinfadi.com.cn/marketanalysis/{}/list/{}.shtml'
START_DATE = '2020-03-10' # 起始时间,包括当前时间
CATAGORY = [{'name': '', 'id': '1'}, # 蔬菜
{'name': '', 'id': '2'}, # 水果
{'name': '', 'id': '3'}, # 肉禽蛋
{'name': '', 'id': '4'}, # 水产
{'name': '', 'id': '5'}, # 粮油
]
def get_page_bs4(url):
response = requests.get(url, HEADER)
return BeautifulSoup(response.text, 'html.parser')
def get_mysql_conn():
conn = pymysql.connect(
host='localhost', port=3306,
user='root', password='pwd',
database='tbname',
charset='utf8')
return conn
# 判断日期是否小于想要抓取的最小日期
def isExpired(date):
return date < START_DATE
# 获取具体数据
def getData(catagory, page_num):
url = BASE_URL.format(catagory, page_num)
bs = get_page_bs4(url)
hq_lst = bs.find('div', class_='hangq_left').find_all('tr')
total_lst = []
for hq in hq_lst:
item_lst = hq.find_all('td')
total_lst.append([x.text for x in item_lst[:-1]])
return total_lst
# 保存到数据库
def saveBatchToDB(conditions):
db = get_mysql_conn()
cursor = db.cursor()
sql = 'INSERT INTO xinfadi(name, lowp, avep, topp, spec, unit, pubdate) VALUES (%s, %s, %s, %s, %s, %s, %s)'
try:
cursor.executemany(sql, conditions)
db.commit()
except:
print('write db error')
db.close()
if __name__ == '__main__':
for cata in CATAGORY:
page_num = 1
isStop = False
while not isStop:
print('\rgetting id:{} page:{}'.format(cata.get('id'), page_num), end='')
item_lst = getData(cata.get('id'), page_num)
page_lst = []
for inx, item in enumerate(item_lst):
if inx == 0:
continue
pub_date = item[-1]
if isExpired(pub_date):
# 碰到第一条早于起始时间的数据,设置终止标记
isStop = True
break
page_lst.append(item)
# 每抓完一页,就存一次数据库
saveBatchToDB(page_lst)
if not isStop:
page_num += 1
print('\rdone', end='')
我爱技术,更爱生活,只要你不“闷”,欢迎来撩