BeautifulSoup4通过lxml使用Xpath定位实例

有以下html。<a>中含有图片链接(可能有多个<a>,每一个都含有一张图片链接)。最后一个<div>中含有文字。

上代码:

复制代码
import requests
from bs4 import BeautifulSoup
from lxml import etree

url='https://www.aaabbbccc.com'
r=requests.get(url)
soup = BeautifulSoup(r.text, 'html.parser')
dom = etree.HTML(str(soup))

my_id='tnews365/31258'

#获取图片链接,放到列表img_url_list中
img_url_list=[]

img_nodes_list=dom.xpath(f"//div[contains(@data-post,'{my_id}')]//a[contains(@class,'tgme_widget_message_photo_wrap')]")

for img_node in img_nodes_list:
    style=img_node.get('style')#图片的链接在style属性中
    #使用正则取出url链接
    img_url_match = r"url\('(.*?)'\)"#注意,匹配(或者)需要使用转义
    slotList = re.findall(img_url_match, style)#此处结果是一个列表
    img_url_list.extend(slotList)

#获取文本内容
text_nodes_list=dom.xpath(f"//div[contains(@data-post,'{my_id}')]//div[contains(@class,'tgme_widget_message_text')]")
try:
    artile_content=text_nodes_list[0].xpath('string(.)')#获取符合条件的div内的文字
except:
    artile_content='本篇无文字内容'

主要知识点:

1、获取指定父节点下的子节点

参考文档:解决xpath定位,获取某个子节点中的某个孩子节点或者文本_xpath当前节点及子节点的文本-CSDN博客

2、获取指定节点下的文本

参考文档:https://www.cnblogs.com/AllenMi/p/14320887.html

相关推荐
ps酷教程6 小时前
Jackson 解决没有无参构造函数的反序列化问题
java
NiceCloud喜云6 小时前
Opus 4.8 的 Effort Control 怎么选:Low 到 Max 五档策略
android·java·大数据·前端·c++·python·spring
wordbaby7 小时前
React Native + RNOH:跨页面数据回传的最佳实践与避坑指南
前端·react native
GISer_Jing7 小时前
Three.js着色器编译机制深度解析
javascript·webgl·着色器
丷丩7 小时前
MapLibre GL JS第22课:查看本地GeoJSON
前端·javascript·map·mapbox·maplibre gl js
油炸自行车7 小时前
Claude Code 错误:API Error: 400 Failed to deserialize the JSON body into the
开发语言·javascript·json·trae·claude code·api error 400
_日拱一卒7 小时前
LeetCode:994腐烂的橘子
java·数据结构·算法·leetcode·深度优先
隔窗听雨眠8 小时前
Nginx网关响应慢排查手记
java·服务器·nginx
智慧物业老杨8 小时前
智慧物业合同周期管理系统:从风险预警到智能交接的全流程数智化落地方案
java·人工智能·python
Front思8 小时前
AI前端工程师需要具备能力+
前端·人工智能·ai