如何在Selenium中使用XPath循环遍历父元素查找对应子元素
亚马逊评论用户名抓取问题修复方案
问题原因
- XPath全局搜索问题:调用
find_element_by_xpath时传入的路径以//开头,无论使用哪个元素对象调用,都会从整个HTML文档的根节点开始搜索,所以每次都返回页面第一个匹配的用户名,导致每页第一个用户名重复出现和评论数相同的次数。 - 代码结构逻辑错误:翻页的while循环嵌套在了第一页的评论遍历for循环内部,会导致第一页每遍历一个评论就重新爬取所有分页的数据,产生大量重复内容。
解决方案
你需要的基于当前review对象查询子元素的方法很简单:XPath路径开头加.代表从当前元素节点开始搜索,而非全局搜索,搭配try-except捕获元素不存在的情况即可,示例如下:
for review in driver.find_elements_by_xpath('//div[@id="cm_cr-review_list"]/div[@data-hook="review"]'): try: # 开头加. 代表在当前review块内搜索 user_name = review.find_element_by_xpath('.//span[@class="a-profile-name"]').text except NoSuchElementException: user_name = "None" name_row.append(user_name)
完整修正后代码
from bs4 import BeautifulSoup import pandas as pd import time from selenium import webdriver from selenium.common.exceptions import NoSuchElementException chromedriver = "path to chromedriver" driver = webdriver.Chrome(chromedriver) url = "https://www.amazon.com/Arti-Cipes-Electric-Cosmetic-Automatic-Machine-Spinner/product-reviews/B08QMKN8Z8/ref=cm_cr_dp_d_show_all_btm?ie=UTF8&reviewerType=all_reviews" driver.get(url) item_name = driver.find_element_by_xpath('//div[@class="a-row product-title"]/h1/a').text name_row = [] while True: # 先爬取当前页所有评论 for review in driver.find_elements_by_xpath('//div[@id="cm_cr-review_list"]/div[@data-hook="review"]'): try: # 相对路径查找当前评论块内的用户名 user_name = review.find_element_by_xpath('.//span[@class="a-profile-name"]').text except NoSuchElementException: user_name = "None" name_row.append(user_name) # 判断是否存在下一页 try: next_page = driver.find_element_by_xpath('//li[@class="a-last"]/a') next_url = next_page.get_attribute('href') driver.get(next_url) # 增加延迟避免触发反爬机制 time.sleep(2) except NoSuchElementException: # 无下一页时退出循环 break df = pd.DataFrame({'Names': name_row}) df.to_csv(item_name + '.csv', index=False) driver.close()
补充说明
该写法每个评论块独立查询内部元素,就算某条评论没有用户名也会插入None占位,后续抓取评分、评论内容等其他字段时,用同样的相对路径在当前review块内查询,就能保证所有字段的顺序完全对应,不会出现错位问题。
内容的提问来源于stack exchange,提问作者DHK
相关产品推荐
相关产品推荐

