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
相关推荐
洛克大航海几秒前
Python 在系统 Windows 和 Ubuntu 中创建虚拟环境
windows·python·ubuntu·虚拟环境
PascalMing2 分钟前
ubuntu 24.04安装dotnet 10日志
linux·运维·ubuntu·dotnet10
ZEERO~2 分钟前
@dataclass的作用
开发语言·windows·python
optimistic_chen7 分钟前
【Docker入门】容器技术
linux·运维·服务器·docker·容器
Lueeee.8 分钟前
2.智梯云枢・全维管控广告系统——解决串口卡顿 + 优化稳定性
linux·运维·服务器
南行*9 分钟前
C语言Linux环境编程
linux·c语言·开发语言·网络安全
海清河晏1119 分钟前
Linux进阶篇:HTTP协议
linux·运维·http
June`12 分钟前
IO模型全解析:从阻塞到异步(高并发的reactor模型)
linux·服务器·网络·c++
几道之旅12 分钟前
pytdx能否下载期货数据呢?
python
晓得迷路了12 分钟前
栗子前端技术周刊第 112 期 - Rspack 1.7、2025 JS 新星榜单、HTML 状态调查...
前端·javascript·html