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
相关推荐
飞猪~15 分钟前
LangChain python 版本 第一集
开发语言·python·langchain
想你依然心痛1 小时前
嵌入式Linux安全加固:SELinux、Capabilities与Seccomp——强制访问控制与沙箱
linux·运维·安全
2601_956319881 小时前
最新AI量化提效,先做可验证的小流程
人工智能·python
REDcker2 小时前
macOS 挂载 Linux 远程目录详解
linux·运维·macos
开飞机的舒克_2 小时前
FastAPI 实战入门:从路由、参数校验到依赖注入的后端开发指南
python·fastapi
2601_961593422 小时前
Mac 上搭建Linux环境吗?VMware + CentOS Stream 9 镜像快速部署
linux·运维·ide·macos·centos
dddwjzx2 小时前
嵌入式Linux C应用编程入门——线程 (二)
linux·嵌入式
霸道流氓气质3 小时前
Kiro 中反编译 JAR 包并分析字节码的流程指南
chrome·python·jar
写代码的学渣3 小时前
Linux systemd 开机启动日志逐行详细解析报告
linux·运维·服务器
人工智能时代 准备好了吗3 小时前
AI回答内容进入率监测:引用识别、文本匹配与语义判断
开发语言·人工智能·python