首页 > 解决方案 > 使用 xpath 查看要抓取的特定元素

问题描述

我正在尝试从网站scamadviser.com 获取一些信息。特别是我对盾牌中的最终分数感兴趣(例如,对于 stackoverflow.com,检查盾牌中的值是 100%)。我试图检查它,我看到路径是:在此处输入图像描述

我做了

def scam(df):
    chrome_options = webdriver.ChromeOptions()

    trust=[]
    country = [] 
    isp_country = [] 
        
    urls=['stackoverflow.com','GitHub.com']
    driver=webdriver.Chrome('mypath',chrome_options=chrome_options))
    
    for x in urls:
        
        wait = WebDriverWait(driver, 20)
        response=driver.get('https://www.scamadviser.com/check-website/'+x)
        
        try: 
            wait = WebDriverWait(driver, 30)
            
            t=driver.execute_script("arguments[0].scrollTop = arguments[0].scrollHeight", driver.find_element_by_xpath("//div[contains(@class,'trust__overlay shield-color--green') and contains(text(),'icon')]")).get_attribute('innerText')
            trust.append(t)  

            c=driver.execute_script("arguments[0].scrollTop = arguments[0].scrollHeight", driver.find_element_by_xpath("//div[contains(@class,'block__col') and contains(text(),'Country')]")).get_attribute('innerText')
            country.append(c)  

           ic=driver.find_element_by_xpath("//div[contains(@class,'block__col') and contains(text(),'ISP')]").get_attribute('innerText')
            isp_country.append(ic)
        
        except: 
            trust.append("Error")
            country.append("Error")
            isp_country.append("Error")
            

    # Create dataframe
    dict = {'URL': urls, 'Trust':trust, 'Country': country, 'ISP': isp_country} 
    df=pd.DataFrame(dict)

    driver.quit()
    
    return df

但是创建的数据框仅包含Errors(即,它仅执行except中的try/except)。

我不明白错误是否是由于 try/except 和/或我查看元素的方式(使用 xpath)造成的。任何帮助都会很棒。谢谢

标签: pythonselenium

解决方案


根据 OP 的响应和此特定票证,trusted score要从 OP 提到的网站获取,以下xpath1/1 matching node in HTML DOM.

Xpath:-

//div[text()='Trustscore']/../following-sibling::div/descendant::div[@class='icon']

您无需滚动查看此 Web 元素,因为一旦启动 Windows,可信分数就在 Selenium 视图端口中。

像这样使用它explicit waits

trusted_score = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//div[text()='Trustscore']/../following-sibling::div/descendant::div[@class='icon']")))
print(trusted_score.text)

为此,您还需要导入。

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

PS:确保 Selenium windows 以全屏模式启动。

driver.maximize_window()

更新 1:

data = {'URL': urls, 
        'Trust': trust, 
        'Country': country, 
        'ISP': isp_country}
df = pd.DataFrame.from_dict(data)

推荐阅读