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
相关推荐
小鸡吃米…34 分钟前
Python PyQt6教程七-控件
数据库·python
椰子今天很可爱35 分钟前
五种I/O模型与多路转接
linux·c语言·c++
Lueeee.1 小时前
Linux kernel Makefile 语法
linux
1916zz1 小时前
Extreme programing 方利喆 _ 江贤晟
python
长安牧笛1 小时前
智能鞋柜—脚气终结者,内置温湿度传感器和紫外线灯,晚上回家,把鞋放进去,自动检测湿度,湿度超标就启动烘干+紫外线杀菌,第二天穿鞋干燥无异味。
python
weixin_457760001 小时前
PIL库将图片位深度是1、8、32统一转换为24的方法
python
Lucky高3 小时前
Pandas库入门
python·pandas
小鸡吃米…3 小时前
Python PyQt6教程三-菜单与工具栏
开发语言·python
爱吃山竹的大肚肚3 小时前
EasyPOI 大数据导出
java·linux·windows
极地星光3 小时前
dmesg 工具的核心功能与作用
linux