爬取北京新发地白菜价代码
以下是一个简单的Python爬虫代码,可以用于爬取北京新发地白菜的价格信息:
import requests
from bs4 import BeautifulSoup
# 发起HTTP GET请求获取网页内容
url = 'http://www.xinfadi.com.cn/marketanalysis/0/list/1.shtml'
response = requests.get(url)
html = response.content
# 使用BeautifulSoup解析网页内容
soup = BeautifulSoup(html, 'html.parser')
# 定位白菜价格所在的表格
table = soup.find('table', class_='hq_table')
# 遍历表格中的每一行
for tr in table.find_all('tr'):
# 获取每一行中的列数据
tds = tr.find_all('td')
if len(tds) == 10:
# 提取白菜的名称和价格
name = tds[0].text.strip()
price = tds[1].text.strip()
# 打印白菜的名称和价格
print('名称:', name)
print('价格:', price)
运行上述代码,即可将北京新发地的白菜价格打印出来。请注意,网页的HTML结构可能会有所变化,导致代码无法正常运行,需要根据实际情况进行调整。此外,爬取网页数据时需要遵守相关法律法规,不能过度频繁地请求网页,以及注意网站的robots.txt文件中的限制

原文地址: http://www.cveoy.top/t/topic/iMD4 著作权归作者所有。请勿转载和采集!