如何使用Python Selenium定位GitHub中指定用户的贡献者区块?
用Selenium定位GitHub贡献者中指定用户的区块
针对你要定位的「GrahamDumpleton」贡献者区块,这里提供几种可靠的定位方式(基于当前GitHub页面DOM结构):
方法1:XPath直接定位完整区块
通过用户名文本向上追溯父容器,XPath表达式可精准匹配到包含目标用户名的整个贡献者条目:
from selenium import webdriver from selenium.webdriver.common.by import By driver = webdriver.Chrome() driver.get("https://github.com/GrahamDumpleton/wrapt/graphs/contributors") # 定位目标用户的贡献者区块 contributor_block = driver.find_element(By.XPATH, '//li[contains(@class, "contributor")]//span[@class="author" and text()="GrahamDumpleton"]/ancestor::li[contains(@class, "contributor")]') # 示例:获取区块内的贡献次数数据 contributions = contributor_block.find_element(By.CSS_SELECTOR, 'span.contrib-number').text print(f"贡献次数:{contributions}")
方法2:先定位用户名再追溯父区块
先找到用户名元素,再通过XPath获取其所属的贡献者容器:
# 定位用户名元素 username_element = driver.find_element(By.CSS_SELECTOR, 'span.author:contains("GrahamDumpleton")') # 向上获取父级贡献者区块 contributor_block = username_element.find_element(By.XPATH, './ancestor::li[contains(@class, "contributor")]')
额外提示:处理动态加载
如果页面需要滚动才加载目标用户区块,可通过等待元素可见确保加载完成:
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC # 最多等待10秒,直到目标区块出现 contributor_block = WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.XPATH, '//li[contains(@class, "contributor")]//span[@class="author" and text()="GrahamDumpleton"]/ancestor::li[contains(@class, "contributor")]')) )
内容的提问来源于stack exchange,提问作者KDWB
相关产品推荐
相关产品推荐

