python网络爬虫(二)——数据的清洗与组织

学会了网络爬虫发送请求后,我们可以获得一段目标的HTML代码,但是还没有把数据提取出来,接下来需要进行数据的清洗与组织。

python 复制代码
for item in data:
    result={
        'title':item.get_test(),
        'link':item.get('href')
    }
    print(result)

首先明确要提取的数据是标题和链接,标题在a标签中,提取标签的正文用get_text()方法;链接在a标签的href属性中,提取标签中的href属性用get()方法,在括号中指定要提取的属性数据,即get('href')

需要使用的正则符合如下:

\d:匹配数字

+:匹配前一个字符1次或多次

在Python中调用正则表达式时使用re库,这个库不用安装,可以直接调用。可以用如下代码:

python 复制代码
import requests
import re
from bs4 import BeautifulSoup

url = 'https://www.bilibili.com/video/BV1TC4y1N7dB/?spm_id_from=333.1007.0.0&vd_source=912d1bec97cad7dac820d2ba865f116a'
strhtml = requests.get(url)
#print(strhtml.text)

soup = BeautifulSoup(strhtml.text,'lxml')
data = soup.select('#main >div >div.mtop.firstMod.clearfix>div.centerBox>ul.newsList>li>a')
print(data)

for item in data:
    result={
        'title':item.get_test(),
        'link':item.get('href')
        'ID:'re.findall('\d+',item.get('href'))
    }
    print(result)
相关推荐
R.lin7 分钟前
Java 8日期时间API完全指南
java·开发语言·python
毕设源码-赖学姐14 分钟前
【开题答辩全过程】以 高校教学质量监控平台为例,包含答辩的问题和答案
java·eclipse
高山上有一只小老虎21 分钟前
翻之矩阵中的行
java·算法
西南胶带の池上桜28 分钟前
1.Pytorch模型应用(线性与非线性预测)
人工智能·pytorch·python
火钳游侠35 分钟前
java单行注释,多行注释,文档注释
java·开发语言
code bean1 小时前
【CMake】为什么需要清理 CMake 缓存文件?深入理解 CMake 生成器切换机制
java·spring·缓存
selt7911 小时前
Redisson之RedissonLock源码完全解析
android·java·javascript
RestCloud1 小时前
智能制造的底层基建:iPaaS 如何统一 ERP、MES 与 WMS 的数据流
java·wms·erp·数据传输·ipaas·mes·集成平台
丘狸尾1 小时前
gradio uv无法add
开发语言·python
guslegend2 小时前
SpringBoot源码剖析
java