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)
相关推荐
CAE虚拟与现实25 分钟前
docker desktop中的build功能是要build什么
java·docker·容器
郝学胜-神的一滴2 小时前
Effective Python 条款 10 :海象运算符_=
开发语言·python·程序人生·开源
wuyk5552 小时前
Python零基础入门第十四章:异常处理(try-except)
开发语言·python
2601_962078192 小时前
Appium+Python+pytest自动化测试框架详解
自动化测试·python·appium·pytest·移动应用
allnlei3 小时前
s6-overlay - 装在 Docker 容器里的轻量级管家
java·docker·容器
卷无止境6 小时前
智能体开发环境ADE浅析,编程工具的下一次范式跃迁
后端·python
IT_Octopus8 小时前
IntelliJ 本地日志路径自定义:`-DLOG_PATH=./logs` 为什么总“不听话“
java·log4j·intellij-idea
长征coder9 小时前
【无标题】
java·性能优化
新时代牛马10 小时前
PCI与PCIe 硬件原理、配置空间/BAR 与 Linux 驱动完整篇:从 LTSSM、TLP 到 ECAM 与probe
java·linux·服务器
2601_9623008110 小时前
机器学习贴士:使用Python编写MapReduce
hadoop·python·机器学习·mapreduce·数据处理