python - 根据 textContent 获取 CSS-selector 或 XPath
问题描述
据我所知,BeautifulSoup 或 scrapy 等 Python 库可以为提供的 CSS 选择器或 XPath 返回文本内容。我正在寻找的是相反的——我想提供一个需要被抓取的文本,并希望获得 CSS-selector 或 XPath 来获取该文本。
这是可以用现有库完成的吗?
html = """
<h1 class="some-class">Article title</h1>
<div class="article-text">
<p class="article-paragraph">Article paragraph text 1.</p>
<p class="article-paragraph">Article paragraph text 2.</p>
</div>
"""
# ... some magic here with get_selector_by_text_content()
article_title_selector = get_selector_by_text_content("Article title", html) # 'h1.some-class'
article_body_selector = get_selector_by_text_content("Article paragraph text 1. \nArticle paragraph text 2.", html) # 'div.article-text > p'
解决方案
如果您可以使用 lxml,您可以获得所提供文本的 xpath:
import lxml.html
from lxml import etree
targets = ['Article title','Article paragraph text 1.','Article paragraph text 2.']
root = lxml.html.fromstring(html)
tree = etree.ElementTree(root)
for e in root.iter():
for target in targets:
if e.text== target:
print(tree.getpath(e))
输出:
/div/h1
/div/div/p[1]
/div/div/p[2]
推荐阅读
- python - 如何在 Python 中为字符串数据构建马尔可夫决策过程模型?
- firebase - Flutter/Firebase - 合并 2 个流并在 PageView Builder 中利用结果
- mongodb - NoSQL/MongoDB:我什么时候需要嵌套对象中的 _id?
- javascript - 当chrome窗口不在焦点时,有没有办法检测用户是否处于活动状态?
- javascript - 带有嵌套数组的 Lodash 合并对象无法正常工作
- java - 无法连接到 Apache Derby 数据库
- c++ - 像 char* const 指针一样分配的数组给出了乱码输出
- jquery - 如何根据models.DateField在django中设置jquery日期选择器的最小日期
- html - 如何使用两种不同的转换来切换课程?
- java - Spring Webflux - 反应式存储库 saveAll(Iterable
) 与 saveAll(Publisher)