AI基础01-文本数据采集

本篇文章是学习文本数据的采集,作为人工智能训练师或者数据分析师有时需要先获取数据,然后进行数据清洗、数据标注。很明显数据采集是后续步骤的基础。

1)数据采集定义

数据采集:data acquisition,DAQ 又称为数据获取,是利用一种装置,从系统外部采集数据并输入系统内部的一个接口。数据采集技术广泛应用于各个领域。

2)数据采集实例

假如我们需要获取佛山市当天的天气情况,像天气是晴天还是多云,天气的气温以及风速。

步骤:请求网站获取HTML信息 ==》使用beautifulsoup解析HTML内容,并找出我们需要的内容 ==》保存到csv 文件中

a、需要安装Requests 库、beautifulsoup库

可以pip install requests

也可以直接在pycharm 里面导入时,提示没有库点击后安装

点击后安装成功,对应的库名下面就没有下划线了:

同样的方法也可以安装别的库。

b、Requests 库使用方法

在Python中,requests模块是一个非常流行的第三方库,用于发送HTTP请求。它提供了一个简单而强大的接口来与HTTP服务器进行交互。

requests.get() 是获取 HTML网页信息的主要方法

r = requests.get(url,params = None,**kwargs):

url:要获取页面的url

params :为字典或者字节序列,作为参数增加到url中

r:为返回的一个包含服务器资源的response对象

import requests

请求天气的网址

url = "https://www.weather.com.cn/weather/101280800.shtml"

r = requests.get(url,timeout=10)

print(r)

print(r.text) #网页上获取的全部内容

c、Beautifulsoup 使用方式

Python中的BeautifulSoup是一个非常流行的库,用于解析HTML和XML文档。它提供了一个简单的API来提取数据。

在使用BeautifulSoup之前,你需要先安装这个库。如果你还没有安装,可以通过pip来安装:pip install beautifulsoup4

导入BeautifulSoup

在你的Python脚本中,首先需要导入BeautifulSoup和解析器(如lxml或html.parser)

from bs4 import BeautifulSoup

解析HTML或XML文档

你可以使用BeautifulSoup类来解析HTML或XML文档。通常,你需要传递文档内容和解析器类型给BeautifulSoup的构造函数。

# 示例HTML文档

html_doc = """

<html>

<head>

<title>The Dormouse's story</title>

</head>

<body>

<p class="title"><b>The Dormouse's story</b></p>

<p class="story">Once upon a time there were three little sisters; and their names were

<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,

<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and

<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;

and they lived at the bottom of a well.</p>

<p class="story">...</p>

</body>

</html>

"""

# 使用html.parser解析器解析HTML文档

soup = BeautifulSoup(html_doc, 'html.parser')

查找元素

BeautifulSoup提供了多种方法来查找元素,包括但不限于:

find(): 返回第一个匹配的标签。

find_all(): 返回所有匹配的标签。

find_parent(), find_parents(): 查找父标签。

find_next_sibling(), find_next_siblings(): 查找下一个兄弟标签。

find_previous_sibling(), find_previous_siblings(): 查找前一个兄弟标签。

select(): 使用CSS选择器查找元素。

示例:使用find()和find_all()

# 查找第一个<a>标签

first_link = soup.find('a')

print(first_link) # <a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>

# 查找所有<a>标签

all_links = soup.find_all('a')

for link in all_links:

print(link) # 打印所有<a>标签的详细信息

示例:使用select()(CSS选择器)

使用CSS选择器查找所有class为"sister"的<a>标签

sisters = soup.select('a.sister')

for sister in sisters:

print(sister['href'], sister.text) # 打印链接和文本内容

获取和修改属性及内容

你可以轻松获取或修改元素的属性或内容。

获取元素的属性值

href = first_link['href'] # 获取href属性值

print(href) # http://example.com/elsie

修改元素的属性值或内容

first_link['href'] = "http://newexample.com/elsie" # 修改href属性值

first_link.string = "Elsie New" # 修改<a>标签内的文本内容为"Elsie New"

3) 编写脚本

获取佛山市当天的天气情况,像天气是晴天还是多云,天气的气温以及风速。

参考代码:

#网页请求函数

def get_html_text(url):

try:

r = requests.get(url,timeout=30)

r.raise_for_status()

r.encoding = 'utf-8'

print("访问网页成功")

return r.text

except:

return "访问异常"

#数据存放到csv文件中

def write_to_csv(file_name,data,day=1):

if not os.path.exists(file_name):

with open(file_name,"w",errors="ignore",newline="") as f:

if day==1:

header = ["最高温度","最低温度","天气情况","风速"]

f_csv = csv.writer(f)

f_csv.writerow(header)

f_csv.writerows(data)

else:

with open(file_name, "a", errors="ignore", newline="") as f:

f_csv = csv.writer(f)

#for i in range(0,len(data)):

f_csv.writerows(data)

#主函数

if name == 'main':

请求天气的网址

url = "https://www.weather.com.cn/weather/101280800.shtml"

csv数据保存文件夹

file_direction = "D:\\dewi\\project2024\\myListPractice\\pythonProject1\\test_data"

打开网页天气预报佛山市

html_text = get_html_text(url)

print(html_text)

使用BeautifulSoup解析HTML内容

soup = BeautifulSoup(html_text, 'html.parser')

获取当天的天气情况

<div class="temperature">25°C</div> 和 <div class="humidity">60%</div>

if soup.find("p", class_="tem").span is None:

temperature_H = "无" #晚上请求的时候可能没有最高温度,这里做了判断

else:

temperature_H = soup.find("p", class_="tem").span.string

temperature_L = soup.find('p', class_='tem').i.string # find()这里返回第一个结果,最低温度

weather = soup.find('p', class_='wea').string #天气状态

wind_speed = soup.find("p", class_="win").i.string #风速

获取的数据放到list

weather_data = []

weather_data.append([temperature_H, temperature_L, weather, wind_speed]) # 列表中包含列表,以便后续写入,或者使用列表中是字典

print("今天天气情况:", weather_data)

#保存到csv文件

write_to_csv(file_direction + "\\weather_data.csv", weather_data, day=1)

4)进阶练习

如何获取最近7天的最低温度呢?

我们可以把它取出来放到列表中。

这里需要使用到find_all(),另外要分清html结构,然后用基本语法就可以实现了:

HTML结构参考如下:

参考代码如下:

import requests
from bs4 import BeautifulSoup

请求天气的网址

url = "https://www.weather.com.cn/weather/101280800.shtml"
r = requests.get(url,timeout=20)
r.encoding = 'utf-8'
print(r)
#print(r.text) #网页上获取的全部内容

soup = BeautifulSoup(r.text,"html.parser")
#练习find()
temprature_low = soup.find("p",class_="tem").i.string
print("第一个最低温度:",temprature_low)

#练习find_all(),7天所有的最低温度
body = soup.body #body内容
data = body.find('div', {'id': '7d'})#7天的数据
ul = data.find('ul') #找到第一个ul
li = ul.find_all('li') #找到所有li
temprature_7days = []
for day in li:
temprature_day = day.find("p",class_="tem").i.string.replace('℃', '') #每天的最低温度
temprature_7days.append(temprature_day) #添加到list.如果是要每天的多个天气情况时,可以使用list包含list形式
print("最近7天的天气最低温度:",temprature_7days)

每天进步一点点,加油!

相关推荐
Silence4Allen6 分钟前
Pycharm 代理配置
ide·python·pycharm·proxy·代理
小安同学iter6 分钟前
苍穹外卖心得体会
java·开发语言·spring boot·servlet·intellij-idea·mybatis
neowell1 小时前
关于PyCharm新版本出现大量空的`jcef_xx.log`文件的解决方法
java·ide·python·pycharm·intellij idea
秋风&萧瑟2 小时前
【QT】QT控制硬件
开发语言·qt
小彭努力中2 小时前
8.Three.js中的 StereoCamera 立体相机详解+示例代码
开发语言·前端·javascript·vue.js·深度学习·数码相机·ecmascript
钢铁男儿4 小时前
Python 重构“策略”模式:用函数简化设计模式的实践
python·设计模式·重构
狐凄4 小时前
Python实例题:ebay在线拍卖数据分析
python·信息可视化·数据分析
柯3495 小时前
JVM-类加载机制
java·开发语言·jvm
风雨无阻fywz5 小时前
java 类的实例化过程,其中的相关顺序 包括有继承的子类等复杂情况,静态成员变量的初始化顺序,这其中jvm在干什么
java·开发语言·jvm
画个大饼6 小时前
Swift中Class和Struct的深度对比分析
开发语言·ios·swift