python爬取近七天的蔬菜价格信息,不要用http://www.xinfadi.com.cn网站
时间: 2024-02-16 16:02:36 浏览: 29
好的,您可以尝试使用其他的数据源,比如国家统计局发布的蔬菜价格信息。以下是一份示例代码,可以爬取近七天的菜价数据:
```python
import requests
from bs4 import BeautifulSoup
from datetime import datetime, timedelta
# 获取当前日期
today = datetime.today().date()
# 构造日期列表
dates = [str(today - timedelta(days=i)) for i in range(7)]
# 构造请求url列表
urls = [
f'http://www.stats.gov.cn/tjsj/tjbz/tjyqhdmhcxhfdm/{date[:4]}/index.html'
for date in dates
]
# 发送请求并解析数据
for url in urls:
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
# TODO: 提取菜价数据并保存
```
这个示例代码中,我们使用了国家统计局的数据源,但是具体的数据提取和保存还需要您根据实际情况进行编写。
相关问题
帮我用python写一个爬取这个页面的产品信息http://www.xinfadi.com.cn/priceDetail.html
这个网站是动态加载数据的,所以我们需要使用 Selenium 模块来模拟浏览器操作,才能获取到完整的数据。下面是一个简单的爬取示例代码,可以获取到每个产品的名称和价格:
```python
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
# 设置 Chrome 浏览器无界面模式
options = Options()
options.add_argument('--headless')
options.add_argument('--disable-gpu')
# 创建 Chrome 浏览器对象
driver = webdriver.Chrome(options=options)
# 打开网页
url = 'http://www.xinfadi.com.cn/priceDetail.html'
driver.get(url)
# 等待数据加载完成
wait = WebDriverWait(driver, 10)
wait.until(EC.presence_of_element_located((By.ID, 'vegtable')))
# 获取每个产品的名称和价格
table = driver.find_element_by_id('vegtable')
rows = table.find_elements_by_tag_name('tr')
for row in rows[1:]:
cols = row.find_elements_by_tag_name('td')
name = cols[0].text
price = cols[1].text
print(name, price)
# 关闭浏览器
driver.quit()
```
需要注意的是,这个网站可能会有反爬措施,请勿频繁访问,以免被封 IP。
Python写北京新发地菜市场爬虫案例
以下是一个简单的Python爬虫代码示例,可以爬取新发地菜市场的价格数据:
```python
import requests
from bs4 import BeautifulSoup
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.36'} # 添加请求头,模拟浏览器访问
response = requests.get(url, headers=headers) # 发送请求,获取网页内容
response.encoding = 'utf-8' # 设置编码方式
html = response.text # 获取网页源代码
soup = BeautifulSoup(html, 'html.parser') # 使用BeautifulSoup解析网页
table = soup.find('table', {'class': 'hq_table'}) # 找到价格表格
trs = table.find_all('tr') # 获取所有的行信息
for tr in trs:
tds = tr.find_all('td') # 获取每一行的单元格信息
if len(tds) > 0:
print(tds[0].text, tds[1].text, tds[2].text, tds[3].text, tds[4].text) # 输出每一行的数据
```
这段代码使用requests库发送请求,BeautifulSoup库解析网页,然后找到价格表格并输出每一行的数据。需要注意的是,爬取网站的数据可能涉及法律风险,使用前请自行了解相关法律法规。