国家水稻数据

国家水稻数据中心

import requests
import parsel
import time
import pandas as pd


def get_rice_data(page=1):
    start = page
    url = f"https://www.ricedata.cn/variety/identified/nation_{start}.htm"
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36"
    }
    res = requests.get(url, headers=headers)
    # 获取网页编码格式并设置
    res.encoding = res.apparent_encoding
    html = parsel.Selector(res.text)
    # 获取父标签
    datas = html.xpath('/html/body/table[2]/tr')

    rice_data = []
    rice_header = ['序号', '品种名称', '亲本来源', '类型', '原产地/选育单位', '审定编号']
    for data in datas[1:]:
        rice_num = data.xpath('td[1]/text()').get()
        rice_category = data.xpath('td[2]/a/text()').get()
        rice_source = data.xpath('td[3]/text()').get()
        rice_type = data.xpath('td[4]/text()').get()
        rice_country = data.xpath('td[5]/text()').get()
        rice_ID = data.xpath('td[6]/text()').get()
        rice_data.append([
            rice_num,
            rice_category,
            rice_source,
            rice_type,
            rice_country,
            rice_ID,
        ])
    rice_data = pd.DataFrame(columns=rice_header, data=rice_data)
    return rice_data


if __name__ == "__main__":
    rice_datas = []
    for l in range(1, 100):
        time.sleep(1)
        print(f"正在获取第{l}页数据")
        data = get_rice_data(l)
        rice_datas.append(data)
    rice_info = pd.concat(rice_datas, ignore_index=True)
    rice_info.to_csv('rice_data.csv', mode='w', index=False, sep=',')
    print("保存成功!")

### 编写Python网页爬虫抓取国家水稻数据 为了实现这一目标,可以采用`BeautifulSoup`和`requests`库来获取并解析HTML页面的内容。对于动态加载内容的情况,则可考虑使用`Selenium`模拟浏览器行为。 #### 准备工作 安装必要的依赖包: ```bash pip install requests beautifulsoup4 selenium pymysql ``` #### 定义项目结构与配置环境变量 创建一个新的Scrapy项目用于管理爬虫逻辑,并设置好MySQL连接参数以便后续存储收集到的数据。 #### 创建Item类定义所需字段 基于给定的需求,在`items.py`文件内声明如下属性[^3]: ```python import scrapy class RiceDataItem(scrapy.Item): news_path = scrapy.Field() news_cate = scrapy.Field() news_title = scrapy.Field() news_date = scrapy.Field() news_source = scrapy.Field() news_guide = scrapy.Field() news_content = scrapy.Field() news_url = scrapy.Field() ``` #### 开发Spider脚本提取具体信息 编写spider模块负责访问指定URL地址(`https://www.ricedata.cn/variety/index.htm`),定位至含有品种详情页链接的位置,随后进入每一个子页面读取详细的资讯记录[^1]: ```python from urllib.parse import urljoin import scrapy from ..items import RiceDataItem class RiceVarietiesSpider(scrapy.Spider): name = "rice_varieties" allowed_domains = ["ricedata.cn"] start_urls = ['https://www.ricedata.cn/variety/index.htm'] def parse(self, response): base_url = 'https://www.ricedata.cn' variety_links = response.xpath('//div[@id="list"]/ul/li/a/@href').getall() for link in variety_links: absolute_link = urljoin(base_url, link.strip()) yield scrapy.Request(absolute_link, callback=self.parse_detail) def parse_detail(self,response): item=RiceDataItem() item['news_path']="稻种资源" item['news_cate']=response.css('.title::text').extract_first().strip() item['news_title']="" item['news_date']="" item['news_source']="中国水稻研究所" item['news_guide']="" item['news_content']=''.join(response.css('p::text').extract()).replace('\u3000',' ').strip() item['news_url']=response.url return item ``` 此段代码实现了对首页列表项的遍历以及单个条目详情页内的文本抽取操作;需要注意的是XPath表达式的选择应当依据实际页面结构调整优化以确保匹配准确性。 #### 存储采集成果至关系型数据库 通过PyMySQL驱动程序建立同MySQL服务器之间的通信链路,将实例化后的对象序列化成字典格式再插入表中保存下来。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值