как навести курсор на несколько элементов с помощью Python - PullRequest
0 голосов
/ 06 октября 2019

Я пытаюсь навести курсор не только на одну точку, но на несколько точек за одной. Точка здесь означает профиль изображения каждого пользователя (их 5 для каждой страницы). Причина, по которой я это делаю, заключается в том, что я пытаюсь проанализировать профиль ссылки каждого пользователя. Но сложность в том, что HTML-коды скрыты. Другими словами, он не появляется, если я не наведу курсор мыши на профиль или фотографию каждого пользователя. Позвольте мне перейти прямо к моему коду.

from selenium.webdriver import ActionChains
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait as wait
from bs4 import BeautifulSoup
from selenium import webdriver

#Incognito Mode
option=webdriver.ChromeOptions()
option.add_argument("--incognito")

#Open Chrome
driver=webdriver.Chrome(executable_path="C:/Users/chromedriver.exe",options=option)

#Get the link
driver.get("https://www.tripadvisor.com/VacationRentalReview-g60742-d7951369-or20-Groove_Stone_Getaway-Asheville_North_Carolina.html")

#This is the first time for me to use Xpath so please understand if there's something wrong with my code
profile=driver.find_element_by_xpath("//div[@class='mainContent']")
profile_pic=profile.find_element_by_xpath("//div[@class='ui_avatar large']")

ActionChains(driver).move_to_element(profile_pic).perform()
ActionChains(driver).move_to_element(profile_pic).click().perform()

profile_box=driver.find_element_by_xpath('//span//a[contains(@href,"/Profile/")]').get_attribute("href")
print (profile_box)

Как мне навести курсор на нескольких пользователей (у которых одинаковые коды Xpath) в этом случае?


=============================== обновленные коды ==========================

num_page=0

#Incognito Mode
option=webdriver.ChromeOptions()
option.add_argument("--incognito")

#Open Chrome
driver=webdriver.Chrome(executable_path="C:/Users/chromedriver.exe",options=option)
driver.implicitly_wait(10)

#Type in URL you want to visit
driver.get("https://www.tripadvisor.com/VacationRentalReview-g60742-d7951369-Groove_Stone_Getaway-Asheville_North_Carolina.html")
driver.maximize_window()
time.sleep(5)

#loop over multiple pages.
for j in range(1,16,1):
    time.sleep(5)
    try:

        #finds all the comments or profile pics
        profile_pic= driver.find_elements(By.XPATH,"//div[@class='prw_rup prw_reviews_member_info_hsx']//div[@class='ui_avatar large']")

        time.sleep(3)

        for i in profile_pic:
                #clicks all the profile pic one by one
                ActionChains(driver).move_to_element(i).perform()
                time.sleep(2)
                ActionChains(driver).move_to_element(i).click().perform()
                time.sleep(4)
                #print the href or link value
                profile_box=driver.find_element_by_xpath('//span//a[contains(@href,"/Profile/")]').get_attribute("href")
                time.sleep(3)
                print (profile_box)
    except:
        pass


    #click the next button to go to the next page.
    link = driver.find_element_by_link_text('Next')
    #Another element is covering the element you are to click.
    #You could use execute_script() to click on this.    
    driver.execute_script("arguments[0].click();", link)

    #After a certain number of pages, use break function to escape from the loop.
    num_page=num_page+1
    if num_page==14:
        break


Благодаря Yosuva A я смог решить, как навести курсор на нескольких пользователей на одной странице имог разобрать данные. Я пытался разработать код так, чтобы я перебирал несколько страниц (каждая страница включает 5 пользователей). Мой обновленный код наверняка перебирает несколько страниц, но в какой-то случайный момент код анализирует только одни и те же ссылки профиля пользователя. Вот выходной пример, который я получаю:

https://www.tripadvisor.com/Profile/Cftra
https://www.tripadvisor.com/Profile/jessicarZ577PF
https://www.tripadvisor.com/Profile/BackPacker115730
https://www.tripadvisor.com/Profile/nanm
https://www.tripadvisor.com/Profile/kukimama
https://www.tripadvisor.com/Profile/ThreeColeys
https://www.tripadvisor.com/Profile/AlanS990
https://www.tripadvisor.com/Profile/S5227HKlisas
https://www.tripadvisor.com/Profile/H1493VRmatthewt
https://www.tripadvisor.com/Profile/H1493VRmatthewt
https://www.tripadvisor.com/Profile/H1493VRmatthewt
https://www.tripadvisor.com/Profile/H1493VRmatthewt
https://www.tripadvisor.com/Profile/H1493VRmatthewt

Я подумал, что мне нужно добавить функцию временного спящего режима, поэтому поместите их в несколько строк, но проблема остается той же. Может ли кто-нибудь помочь мне, и это происходит, и как преодолеть это? Спасибо.

1 Ответ

1 голос
/ 06 октября 2019

Пример Python

Этот код будет щелкать все картинки профиля по одному и печатать значение href.

import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
driver = webdriver.Chrome('/usr/local/bin/chromedriver')  # Optional argument, if not specified will search path.
driver.implicitly_wait(15)

driver.get("https://www.tripadvisor.com/VacationRentalReview-g60742-d7951369-or20-Groove_Stone_Getaway-Asheville_North_Carolina.html");

#finds all the comments or profile pics
profile_pic= driver.find_elements(By.XPATH,"//div[@class='prw_rup prw_reviews_member_info_hsx']//div[@class='ui_avatar large']")

for i in profile_pic:
        #clicks all the profile pic one by one
        ActionChains(driver).move_to_element(i).perform()
        ActionChains(driver).move_to_element(i).click().perform()
        time.sleep(2)
        #print the href or link value
        profile_box=driver.find_element_by_xpath('//span//a[contains(@href,"/Profile/")]').get_attribute("href")
        print (profile_box)

driver.quit()

Вывод

https://www.tripadvisor.com/Profile/861kellyd
https://www.tripadvisor.com/Profile/JLERPercy
https://www.tripadvisor.com/Profile/rayn817
https://www.tripadvisor.com/Profile/grossla
https://www.tripadvisor.com/Profile/kapmem

Пример Java

import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

public class Selenium {

    public static void main(String[] args) {
        System.setProperty("webdriver.chrome.driver", "./lib/chromedriver");
        WebDriver driver = new ChromeDriver();
        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        driver.get("https://www.tripadvisor.com/VacationRentalReview-g60742-d7951369-or20-Groove_Stone_Getaway-Asheville_North_Carolina.html");

        //finds all the comments or profiles
        List<WebElement> profile= driver.findElements(By.xpath("//div[@class='prw_rup prw_reviews_member_info_hsx']//div[@class='ui_avatar large']"));

        for(int i=0;i<profile.size();i++)
        {
            //Hover on user profile photo
            Actions builder = new Actions(driver);
            builder.moveToElement(profile.get(i)).perform();
            builder.moveToElement(profile.get(i)).click().perform();
            //Wait for user details pop-up
            WebDriverWait wait = new WebDriverWait(driver, 10);
            wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//span//a[contains(@href,'/Profile/')]")));
            //Extract the href value
            String hrefvalue=driver.findElement(By.xpath("//span//a[contains(@href,'/Profile/')]")).getAttribute("href");
            //Print the extracted value
            System.out.println(hrefvalue);
        }
        //close the browser
        driver.quit(); 

    }

}
...