有没有什么方便的方法来获取页面中的子节索引?

2024-10-01 09:39:38 发布

您现在位置:Python中文网/ 问答频道 /正文

使用“index-x”可以方便地快速定位页面中的子节

例如

https://docs.python.org/3/library/re.html#index-2

给出了page中的第3小节

当我想把一个子节的位置分享给其他人时,如何方便地获得索引

例如,如何获得{m,n}子节的索引而不从index-0开始计数

enter image description here


Tags: httpsorg定位redocsindexhtmllibrary
2条回答

对于bs4.7.1,您可以使用:has:contains以特定文本字符串为目标并返回索引(注意,使用select_one将返回第一个匹配项)。如果要返回所有匹配项,请使用列表理解和select

import requests
from bs4 import BeautifulSoup as bs

r = requests.get('https://docs.python.org/3/library/re.html')
soup = bs(r.content, 'lxml')
index = soup.select_one('dl:has(.pre:contains("{m,n}"))')['id']
print(index)

任何版本:如果你想要一个字典,映射特殊字符到索引。感谢@zoe发现了我字典理解中的错误

import requests
from bs4 import BeautifulSoup as bs

r = requests.get('https://docs.python.org/3/library/re.html')
soup = bs(r.content, 'lxml')
mappings = dict([(item['id'], [i.text for i in item.select('dt .pre')]) for item in soup.select('[id^="index-"]')])
indices = {i: k for (k, v) in mappings.items() for i in v}

你在找index-7

您可以下载页面的HTML并使用以下代码获取index-something的所有可能值:

import re
import requests
from bs4 import BeautifulSoup

r = requests.get('https://docs.python.org/3/library/re.html')
soup = BeautifulSoup(r.content.decode())

result = [t['id'] for t in soup.find_all(id=re.compile('index-\d+'))]

print(result)

输出:

['index-0', 'index-1', 'index-2', 'index-3', 'index-4', 'index-5', 'index-6', 'index-7', 'index-8', 'index-9', 'index-10', 'index-11', 'index-12', 'index-13', 'index-14', 'index-15', 'index-16', 'index-17', 'index-18', 'index-19', 'index-20', 'index-21', 'index-22', 'index-23', 'index-24', 'index-25', 'index-26', 'index-27', 'index-28', 'index-29', 'index-30', 'index-31', 'index-32', 'index-33', 'index-34', 'index-35', 'index-36', 'index-37', 'index-38']

列表理解中的t对象包含id与regex匹配的标记的HTML

相关问题 更多 >