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