python html 解析的一些写法

python 复制代码
import requests
from lxml import etree
# 1. 请求网页
url = '链接'
res = requests.get(url)
# 2. 解析网页内容
tree = etree.HTML(res.text)
# 3. 提取数据
ls = tree.xpath('//dl[@class="textList"]//a')
for i in ls:
# 基于当前标签对象获取文本及属性
    name = i.xpath('./text()')[0]
    detail_url = i.xpath('./@href')[0]
    
    下面是获取到内容页后得到页面数据组后操作
    text_ls = p.xpath('.//text()')
    print(''.join(text_ls).replace('\r\n','').replace(' ',''))
python 复制代码
import requests
#from lxml import etree
from bs4 import BeautifulSoup
url="链接"
headers={
    'user-agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36'
}
res=requests.get(url,headers=headers)
res.encoding='utf-8'
#print(res.text)
#创建BeautifulSoup对象
#BeautifulSoup(html字符串数据,html的解析器)
bs=BeautifulSoup(res.text,'lxml')
lis=bs.select('#browserItemList li')
#print(ls)
count=1
for item in lis:
    title=item.find('a',class_="l").text
    des=item.find('p',class_='info tip').text.replace('\n','').replace('\r','').replace(' ','')
    fade=item.find('small',class_="fade").text
    ren=item.find('span',class_="tip_j").text

    print(count,title,des,fade,ren)
    count+=1

安装模块

复制代码
lxml :解析器              pip install lxml
复制代码
pip install beautifulsoup4
相关推荐
知识分享小能手2 小时前
openEuler入门学习教程,从入门到精通,openEuler 24.03 中的 Vim 编辑器 —— 全面知识点详解(7)
linux·vim·openeuler
西猫雷婶2 小时前
CNN的四维Pytorch张量格式
人工智能·pytorch·python·深度学习·神经网络·机器学习·cnn
未来之窗软件服务2 小时前
幽冥大陆(二十三)python语言智慧农业电子秤读取——东方仙盟炼气期
开发语言·python·仙盟创梦ide·东方仙盟·东方仙盟sdk·东方仙盟浏览器
程序员三藏2 小时前
Web自动化测试详细流程和步骤
自动化测试·软件测试·python·selenium·测试工具·职场和发展·测试用例
数据知道2 小时前
FastAPI基础项目:仿头条新闻的web项目,实现基本的新闻列表页和详情页查看功能
前端·python·fastapi·python项目
2501_941111252 小时前
自动化与脚本
jvm·数据库·python
LCG元2 小时前
Linux 性能监控三板斧:top/vmstat/iostat 快速入门
linux
LCG元2 小时前
实战案例:服务器磁盘空间告急,如何快速定位和清理"大文件"
linux
以琦琦为中心3 小时前
很好!从 `fdisk -l` 输出可以看到您的磁盘确实是600GB,但只有29.5GB被分配给根分区 `/dev/sda3`。现在我来帮您扩展这个分区。
linux·ubuntu