【发布时间】:2020-11-08 20:17:16
【问题描述】:
我正在尝试从https://www.msamb.com/ApmcDetail/ArrivalPriceInfo 网站上抓取数据。
这是我要抓取的数据。因此,在突出显示的下拉选择框中有 148 种商品。
到目前为止,我通过选择每个单独的商品来手动复制数据。提取数据需要大量手动操作。
所以,为了让它自动化,我开始使用 Python。 以下是我在 Python (3.7.8) 代码中使用的库。
- 硒
- 美汤
- 熊猫
这是我的 Python 代码。
from selenium import webdriver
from bs4 import BeautifulSoup
import pandas as pd
from selenium.webdriver.support.ui import Select
#from selenium.webdriver.common.by import By
driver = webdriver.Chrome(executable_path='G:/data/depend/chromedriver.exe')
driver.get('https://www.msamb.com/ApmcDetail/ArrivalPriceInfo/')
commodity = Select(driver.find_element_by_id("CommoditiesId"))
#able to select commodities by value
commodity.select_by_value('08005')
# Iterating over the all the commodity an fetching <td> element
for option in commodity.options:
#print(option.text)
soup = BeautifulSoup(option.text)
print(soup)
rows = soup.select('tr')
print(rows)
for row in rows[1:]:
td = row.find_all('td')
print(td)
APMC = td[0].text.strip()
print(APMC)
在这里,我可以从下拉选择框中通过 id 等于 CommoditiesId 来获取商品。
获取商品列表 (148) 后,我将尝试解析为该特定商品获取的 HTML 表格内容。在这里,我可以打印每次迭代的商品名称,但无法打印 APMC、品种、单位、数量、Lrate、Hrate、Modal 列数据。
如果以上解决了,我希望以~|~ 分隔格式输出,并希望添加两列,即日期、商品。
因此,示例输出将如下所示(截至目前,手动准备以下数据文件)。
Date~|~Commodity~|~APMC~|~Variety~|~Unit~|~Quantity~|~Lrate~|~Hrate~|~Modal
2020-07-11~|~APPLE~|~KOLHAPUR~|~QUINTAL~|~17~|~8500~|~14500~|~11500
2020-07-11~|~APPLE~|~CHANDRAPUR-GANJWAD~|~QUINTAL~|~9~|~15000~|~17000~|~16000
2020-07-11~|~APPLE~|~NASHIK~|~DILICIOUS- No.1~|~QUINTAL~|~60~|~9500~|~16000~|~13000
2020-07-11~|~AMBAT CHUKA~|~PANDHARPUR~|~~|~NAG~|~7~|~10~|~10~|~10
2020-07-10~|~AMBAT CHUKA~|~PUNE-MANJRI~|~~|~NAG~|~400~|~3~|~6~|~4
2020-07-10~|~AMBAT CHUKA~|~PUNE~|~LOCAL~|~NAG~|~1300~|~4~|~5~|~4
【问题讨论】:
标签: python pandas selenium web-scraping beautifulsoup