python_读数据采集day1

本文介绍了如何使用BeautifulSoup库解析HTML文档,包括查找特定标签、提取属性、处理兄弟标签及利用set去重爬取等功能,并展示了基维百科的爬虫实例。
一、find_all 属性记录
def find_all(self, name=None, attrs={}, recursive=True, text=None,
             limit=None, **kwargs):
name:标签名字
attrs:标签中的属性值 例子:{‘class’:‘split’}
recursive:递归默认为True
text:根据网页内容查询 例子:<p></p>
limit:范围限制参数 limit,显然只用于 findAll 方法。find 其实等价于 findAll 的 limit 等于 1 时的情形。如果你只对网页中获取的前 x 项结果感兴趣,就可以设置它。但是要注意, 这个参数设置之后,获得的前几项结果是按照网页上的顺序排序的,未必是你想要的那 前几项。
kwargs:选择那些具有指定属性的标签 例子:bsObj.findAll(id="text") 和 bsObj.findAll("", {"id":"text"})相同
二、Navigablestring 和 Comment 两个对象
from bs4 import Comment
用来表示标签里的文字
from bs4 import NavigableString
用来查找 HTML 文档的注释标签,<!-- 像这样 -->

三 、next_siblings()函数 处理兄弟标签例子table:
处理后的结果不包含第一层tr 的所有tr
选择标签行然后调用 next_siblings,可以选择表 格中除了标题行以外的所有行。
import requests
from bs4 import BeautifulSoup
html = requests.get("http://www.pythonscraping.com/pages/page3.html").text
soup = BeautifulSoup(html,'html.parser')
for  i in soup.find("table",{"id":"giftList"}).tr.next_siblings:
    print(i)

四、基维百科六分割
import requests
import re
from bs4 import BeautifulSoup
import random
import  datetime
#产生随机种子,相同的随机种子容易产生相同的随机数,用时间做随机种子
random.seed(datetime.datetime.now())
def getLink(a):
    r=requests.get('http://en.wikipedia.org'+a)
    print(r.status_code)
    html =r.text
    soup = BeautifulSoup(html,"html.parser")
    #找取a标签
    #/wiki/%E5%87%AF%E6%96%87%C2%B7%E8%B4%9D%E8%82%AF
    links = soup.find('div',id='bodyContent').find_all('a',href=re.compile("^(/wiki/)((?!:).)*$"))
    return links
links = getLink("/wiki/Kevin_Bacon")
while len(links)>0:
    #随机种子产生随机
    print(len(links))
    href = links[random.randint(0,len(links)-1)]['href']
    print(href)
    links = getLink(href)
四、利用set 去重爬取
import requests
import re
from bs4 import BeautifulSoup
pages =set()
def getLinks(pageUrl):
#设置全局变量用外围的set进行存取
    global pages
    r=requests.get("http://en.wikipedia.org"+pageUrl)
    html = r.text
    soup = BeautifulSoup(html,'html.parser')
    for link in soup.find_all("a",href=re.compile("^(/wiki/)")):
        if 'href' in link.attrs:
            if link.attrs['href'] not in pages:
                newPage = link.attrs['href']
                print(newPage)
                pages.add(newPage)
                getLinks(newPage)
getLinks("")

五、针对属性的异常处理
import requests
from bs4 import BeautifulSoup
import re

page = set()
def getLink(pageUrl):
    global page
    r=requests.get("http://en.wikipedia.org"+pageUrl)
    html = r.text
    soup = BeautifulSoup(html,'html.parser')
    #属性的异常处理重点
    try:
        print(soup.h1.get_text())
        print(soup.find(id='mw-content-text').find('p'))
        print(soup.find(id="ca-edit").find("span").find("a").attrs['href'])
    except AttributeError:
        print("缺少属性")

    for links in  soup.findAll("a", href=re.compile("^(/wiki/)")):
        if 'href' in links.attrs:
            if links['href'] not in page:
                newpageurl = links['href']
                page.add(newpageurl)
                getLink(newpageurl)
getLink("")




<think>嗯,用户问的是如何用Python实现天气数据采集。首先,我需要理解用户的需求。可能他们想做一个天气应用,或者需要天气数据进行分析。那得先确定数据来源,常见的天气API有OpenWeatherMap、AccuWeather、和风天气等。这些API通常需要注册获取API key。 接下来,用户可能需要知道具体的步骤。比如,如何用Python发送HTTP请求,处理返回的数据。可能需要用到requests库。然后解析数据,通常是JSON格式,所以json模块也是必要的。还要考虑错误处理,比如网络问题或API限制。 用户可能不熟悉API的使用,需要详细说明如何注册和获取API key。比如,以OpenWeatherMap为例,步骤可能是:注册账号,创建API key,然后使用这个key构造请求URL。然后,用requests.get()发送请求,检查响应状态码,200的话就解析JSON数据,提取需要的天气信息。 另外,用户可能希望有一个代码示例,这样他们可以快速上手。代码应该包括导入库、构造请求URL、发送请求、处理响应、提取数据这几个部分。还要注意异常处理,比如用try-except块来捕获可能的错误,比如连接错误、超时等。 可能还需要提醒用户注意API的使用限制和费用,比如免费层的调用次数限制,避免超额使用导致额外费用或被封禁。此外,数据解析部分要具体,比如如何从返回的JSON中获取温度、湿度、风速等信息,可能需要给出具体的字段路径。 另外,用户可能对数据存储感兴趣,比如将采集的数据保存到CSV文件或数据库中。这部分可以简要提及,比如使用csv模块或sqlite3模块,但可能不是主要问题,所以放在扩展部分。 最后,要确保整个解释清晰,步骤明确,代码可运行。可能需要检查代码中的变量名是否正确,API key的替换提示是否到位。同时,用中文回答,避免专业术语过多,必要时解释关键点,比如API key的作用,JSON的结构等。</think>Python实现天气数据采集通常分为以下步骤,以OpenWeatherMap API为例: 1. **获取API密钥** - 访问 https://openweathermap.org 注册账号 - 在控制面板创建API Key(免费版每天可调用60次) 2. **安装依赖库** ```bash pip install requests ``` 3. **基础代码实现** ```python import requests import json def get_weather(api_key, city): base_url = "http://api.openweathermap.org/data/2.5/weather" params = { "q": city, "appid": api_key, "units": "metric" # 摄氏温度 } try: response = requests.get(base_url, params=params) response.raise_for_status() # 检查HTTP错误 weather_data = response.json() if weather_data["cod"] != 200: raise Exception(f"API Error: {weather_data['message']}") return { "城市": weather_data["name"], "温度": weather_data["main"]["temp"], "天气": weather_data["weather"][0]["description"], "湿度": weather_data["main"]["humidity"], "风速": weather_data["wind"]["speed"] } except requests.exceptions.RequestException as e: print(f"请求错误: {e}") except KeyError as e: print(f"数据解析错误: {e}") return None # 使用示例 API_KEY = "your_api_key_here" # 替换为实际API Key city = "Beijing" weather = get_weather(API_KEY, city) print(json.dumps(weather, indent=2, ensure_ascii=False)) ``` 4. **扩展功能建议** - 数据存储:使用SQLite/MySQL保存历史数据 ```python import sqlite3 def save_to_db(data): conn = sqlite3.connect('weather.db') c = conn.cursor() c.execute('''CREATE TABLE IF NOT EXISTS weather (city TEXT, temp REAL, humidity INTEGER, timestamp DATETIME DEFAULT CURRENT_TIMESTAMP)''') c.execute("INSERT INTO weather (city, temp, humidity) VALUES (?, ?, ?)", (data['城市'], data['温度'], data['湿度'])) conn.commit() conn.close() ``` - 定时采集:结合schedule库定时执行 ```python import schedule import time def daily_job(): weather = get_weather(API_KEY, city) save_to_db(weather) schedule.every().day.at("09:00").do(daily_job) while True: schedule.run_pending() time.sleep(1) ``` **注意事项**: 1. API调用频率需遵守服务商限制 2. 建议添加异常重试机制 3. 敏感信息(API Key)应使用环境变量存储 4. 免费API通常有历史数据限制,商业项目需购买高级套餐 其他数据源推荐: - 和风天气(国内服务) - 国家气象局API - 爬虫获取气象网站数据(需遵守robots.txt) 如果需要更详细的实现方案或遇到具体问题,可以告诉我您的具体需求,例如: - 需要采集哪些具体气象要素? - 需要实时数据还是历史数据? - 数据采集的频率要求? 我可以提供更有针对性的建议。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值