Python 爬取北京新发地菜价代码示例
以下是一个简单的 Python 代码示例,用于爬取北京新发地菜价信息:
import requests
from bs4 import BeautifulSoup
def get_caijia():
url = 'http://www.xinfadi.com.cn/marketanalysis/0/list/1.shtml'
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}
response = requests.get(url, headers=headers)
response.encoding = 'utf-8'
soup = BeautifulSoup(response.text, 'html.parser')
table = soup.find('table', class_='hq_table')
rows = table.find_all('tr')
for row in rows[1:]:
cols = row.find_all('td')
name = cols[0].text.strip()
low_price = cols[1].text.strip()
avg_price = cols[2].text.strip()
high_price = cols[3].text.strip()
gui_ge = cols[4].text.strip()
date = cols[5].text.strip()
print(f'品名:{name} 最低价:{low_price} 平均价:{avg_price} 最高价:{high_price} 规格:{gui_ge} 日期:{date}')
if __name__ == '__main__':
get_caijia()
运行上述代码,可以输出北京新发地的菜价信息。需要安装 requests 和 beautifulsoup4 库来运行这段代码。
原文地址: https://www.cveoy.top/t/topic/qsQh 著作权归作者所有。请勿转载和采集!