python抓取新发地菜价一页的代码怎么写
时间: 2024-03-02 14:27:27 浏览: 16
以下是一个简单的 Python 代码示例,用于从新发地网站抓取一个页面的菜价数据:
```python
import requests
from bs4 import BeautifulSoup
# 指定要抓取的页面URL
url = 'http://www.xinfadi.com.cn/marketanalysis/0/list/1.shtml'
# 发送HTTP请求并获得响应内容
response = requests.get(url)
html = response.text
# 使用BeautifulSoup解析HTML页面
soup = BeautifulSoup(html, 'html.parser')
# 定位到菜价表格
table = soup.find('table', class_='hq_table')
# 遍历表格中的所有行,并提取每行的菜价数据
for row in table.find_all('tr'):
# 跳过表头行
if '品种' in row.get_text():
continue
# 提取每行的菜价数据
cells = row.find_all('td')
name = cells[0].get_text()
low_price = cells[1].get_text()
avg_price = cells[2].get_text()
high_price = cells[3].get_text()
unit = cells[4].get_text()
# 输出菜价数据
print(name, low_price, avg_price, high_price, unit)
```
以上代码使用 requests 库发送 HTTP 请求,使用 BeautifulSoup 库解析 HTML 页面,然后从菜价表格中提取每行的菜价数据,并将其打印到控制台。请注意,此示例仅抓取了一个页面,并只提取了表格中的前五列数据。如果需要抓取更多页面或提取更多数据,请根据实际情况进行扩展。