Same kind of item but with different kinds of Xpath

Question:

I’m trying to crawl all the comments from a website. But the problem is some comments have different xpath structures. For example:

Item 1:

//*[@id="__next"]/div[1]/main/div[3]/div[4]/div/div[2]/div[3]/div[2]/div[3]/text()

Item 2:

//*[@id="__next"]/div[1]/main/div[3]/div[4]/div/div[2]/div[4]/div[2]/div[3]/div/span[1]/text()

Item 3:

//*[@id="__next"]/div[1]/main/div[3]/div[4]/div/div[2]/div[5]/div[2]/div[3]/text()

I’m really confused by this problem, I hope I can receive a suitable response as soon as posible. Here’s the URL: https://tiki.vn/khong-diet-khong-sinh-dung-so-hai-tb5-p187827003.html?spid=187827005

Asked By: Avry G.

||

Answers:

Use this relative XPATH expression:

//div[@class='review-comment__content']

Full working code:

driver = webdriver.Chrome()
driver.maximize_window()
driver.implicitly_wait(10)
driver.get("https://tiki.vn/khong-diet-khong-sinh-dung-so-hai-tb5-p187827003.html?spid=187827005")
# below line scrolls down the page
driver.execute_script("scroll(0, 1600)")
time.sleep(5)
# below line stores all comments into the variable commentsList
commentsList = driver.find_elements(By.XPATH, "//div[@class='review-comment__content']")
print(len(commentsList))
for x in range (len(commentsList)):
    print(commentsList[x].text)

Console output:

5
"Vô thường là nhìn vào thực tại trong khía cạnh thời gian. Vô ngã là nhìn trong bình diện không gian"/ Tr 61
" Bụt dạy rằng khi có đủ nhân duyên thì bạn biểu hiện. Khi nhân duyên không đủ nữa, bạn sẽ ngưng hiện hữu để có thể xuất hiện dưới các hình tướng khác, trong những điều kiện khác."/ Tr 87
- Mình bất ngờ bởi bìa sách siêu sắc nét, mỗi khi nhìn vào mình cảm nhận như thầy đang hiện diện.
- Trang giấy có hơi mỏng nhưng giấy màu ngà vàng tốt cho mắt.
- Do là bản dịch lại nên đôi khi mình thấy việc đọc không được mượt mà lắm, tuy nhiên không ảnh hưởng đến ý nghĩa của thầy muốn truyền tải
Cuốn sách rất đẹp, giấy xịn, mượt, trơn, cực kì thích luôn ạ. Tiki giao hàng rất nhanh, mới đặt ngày sau đã có rùi ❤❤❤
Sách được bọc nilông cẩn thận giao hàng rất nhanh trong vòng một ngày nội dung sách thì mình chưa đọc nên chưa thể nhận xét nhưng đã có rất nhiều YouTuber review Đánh giá với số điểm cao nên mình quyết định mua
Đây là 1 quyển sách nhiều ý nghĩa của thầy Thích Nhất Hạnh. Sách giúp mình hiểu rằng mọi thứ trên cuộc đời ko có sinh cũng ko có mất, đủ nhân duyên thì biểu hiện, ko đủ nhân duyên thì ẩn tàng

Process finished with exit code 0

Explanation:
The comments won’t be visible until you scroll down the page, you need to imitate this in your selenium script. First scroll down the page, then using the relative XPATH provided, store all the comments into a variable. Then print the list.

Answered By: Shawn
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.