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
相关推荐
松涛和鸣8 分钟前
72、IMX6ULL驱动实战:设备树(DTS/DTB)+ GPIO子系统+Platform总线
linux·服务器·arm开发·数据库·单片机
简单中的复杂34 分钟前
【避坑指南】RK3576 Linux SDK 编译:解决 Buildroot 卡死在 host-gcc-final 的终极方案
linux·嵌入式硬件
gpfyyds66639 分钟前
Python代码练习
开发语言·python
wVelpro1 小时前
如何在Pycharm 2025.3 版本实现虚拟环境“Make available to all projects”
linux·ide·pycharm
程序员老舅2 小时前
C++高并发精髓:无锁队列深度解析
linux·c++·内存管理·c/c++·原子操作·无锁队列
雨中风华2 小时前
Linux, macOS系统实现远程目录访问(等同于windows平台xFsRedir软件的目录重定向)
linux·windows·macos
aiguangyuan2 小时前
使用LSTM进行情感分类:原理与实现剖析
人工智能·python·nlp
小小张说故事2 小时前
BeautifulSoup:Python网页解析的优雅利器
后端·爬虫·python
luoluoal2 小时前
基于python的医疗领域用户问答的意图识别算法研究(源码+文档)
python
Shi_haoliu2 小时前
python安装操作流程-FastAPI + PostgreSQL简单流程
python·postgresql·fastapi