如何用Selenium从多元素中获取多属性?爬取用户名与用户ID
解决方案
你需要遍历find_elements返回的元素列表,逐个获取每个元素的href属性,再从链接中解析出用户名和用户ID。以下是修改后的代码:
from selenium import webdriver from selenium.webdriver.common.by import By driver.get("https://tinhte.vn/thread/tong-hop-16-tin-don-moi-nhat-ve-iphone-16.3739136/") # 获取所有包含/profile/的链接元素 profile_elements = driver.find_elements(By.XPATH, "//*[contains(@href, '/profile/')]") # 用字典存储,自动去重同一用户 user_info = {} for element in profile_elements: href = element.get_attribute("href") if href: # 从链接末尾拆分出用户名和ID,比如"username.123456/" profile_part = href.split("/profile/")[-1].rstrip("/") username, user_id = profile_part.split(".") user_info[username] = user_id # 打印结果 for username, user_id in user_info.items(): print(f"用户名: {username}, 用户ID: {user_id}")
关键说明:
find_elements返回的是元素列表,必须通过循环遍历每个元素,才能调用get_attribute获取单个元素的属性值- 使用字典
user_info存储数据,避免重复抓取同一用户的信息 - 通过字符串拆分解析链接:先拆分出
/profile/后的部分,再用.分割得到用户名和用户ID
内容的提问来源于stack exchange,提问作者likenzy
相关产品推荐
相关产品推荐

