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

相关推荐
摘星编程5 小时前
OpenHarmony + RN:Placeholder文本占位
javascript·react native·react.js
a1117765 小时前
医院挂号预约系统(开源 Fastapi+vue2)
前端·vue.js·python·html5·fastapi
0思必得05 小时前
[Web自动化] Selenium处理iframe和frame
前端·爬虫·python·selenium·自动化·web自动化
virus59456 小时前
悟空CRM mybatis-3.5.3-mapper.dtd错误解决方案
java·开发语言·mybatis
没差c7 小时前
springboot集成flyway
java·spring boot·后端
时艰.7 小时前
Java 并发编程之 CAS 与 Atomic 原子操作类
java·开发语言
行走的陀螺仪7 小时前
uni-app + Vue3编辑页/新增页面给列表页传参
前端·vue.js·uni-app
编程彩机7 小时前
互联网大厂Java面试:从Java SE到大数据场景的技术深度解析
java·大数据·spring boot·面试·spark·java se·互联网大厂
笨蛋不要掉眼泪7 小时前
Spring Boot集成LangChain4j:与大模型对话的极速入门
java·人工智能·后端·spring·langchain
Yvonne爱编码8 小时前
JAVA数据结构 DAY3-List接口
java·开发语言·windows·python