Python 如何使用selenium从A标记中获取文本?

Python 如何使用selenium从A标记中获取文本?,python,selenium,selenium-webdriver,text,getattribute,Python,Selenium,Selenium Webdriver,Text,Getattribute,我一直试图在网上搜刮一些产品,但当我尝试从A标签打印标题时,它会给我这个输出 这是我的密码 from selenium import webdriver from selenium.webdriver.common.keys import Keys import pandas as pd PATH = "C:\Program Files (x86)\chromedriver.exe" driver = webdriver.Chrome(PATH) driver.ge

我一直试图在网上搜刮一些产品,但当我尝试从A标签打印标题时,它会给我这个输出

这是我的密码

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import pandas as pd  

PATH = "C:\Program Files (x86)\chromedriver.exe"

driver = webdriver.Chrome(PATH)
driver.get("https://egypt.souq.com")

dotd = "/html/body/div[2]/div/main/div[1]/div[1]/div/div[1]/a/img"

driver.find_element_by_xpath(dotd).click()

def get_deals():
    title_xpath = "/html/body/div[1]/div/main/div/div[4]/div[3]/div[2]/div[1]/div[1]/div/div[2]/ul/li[1]/h6/span/a"
    titles = driver.find_elements_by_xpath(title_xpath)
    for title in titles:
        print(title)


get_deals()
print("successful")

问题是您正在打印包含所有属性的对象,而不是文本属性


因此,唯一需要更改的是,不要使用
print(title)
,而是使用
print(title.text)

问题是您正在打印包含所有属性的对象,而不是text属性


因此,您唯一需要更改的是,不要使用
print(title)
,而是使用
print(title.text)

这个来自
print()的输出

<selenium.webdriver.remote.webelement.WebElement (session="48e7924c296324a7a5a843d9ccab36fb", element="b8871651-23af-42c6-a49a-5b93fe932653")>
  • 使用
    get\u attribute()
    属性:

    for title in titles:
        print(title.text)
    
    for title in titles:
        print(title.get_attribute("innerHTML"))
    

  • 参考文献 您可以在以下内容中找到一些相关讨论:


    此输出来自
    print()

    <selenium.webdriver.remote.webelement.WebElement (session="48e7924c296324a7a5a843d9ccab36fb", element="b8871651-23af-42c6-a49a-5b93fe932653")>
    
  • 使用
    get\u attribute()
    属性:

    for title in titles:
        print(title.text)
    
    for title in titles:
        print(title.get_attribute("innerHTML"))
    

  • 参考文献 您可以在以下内容中找到一些相关讨论:


    成功了!但它只打印一个标题,即使页面有多个标题titles@RazerPYOfficial很高兴能帮助你。但这听起来是一个不同的问题。你能用你的新要求提出一个新问题吗?我发布了另一个question@RazerPYOfficial很高兴能帮助你。你发现这对未来读者的利益很有帮助。看,成功了!但它只打印一个标题,即使页面有多个标题titles@RazerPYOfficial很高兴能帮助你。但这听起来是一个不同的问题。你能用你的新要求提出一个新问题吗?我发布了另一个question@RazerPYOfficial很高兴能帮助你。你发现这对未来读者的利益很有帮助。看见