【问题标题】:Python Selenium: get_attribute returns None but the attribute existsPython Selenium:get_attribute 返回 None 但属性存在
【发布时间】:2020-07-01 07:21:27
【问题描述】:

我正在尝试从 Google 图片中抓取图片。我的代码:

from selenium import webdriver
import time

keyword = "cats"
url = "https://www.google.com/search?q=" + keyword + "&source=lnms&tbm=isch&tbs="

driver= webdriver.Chrome()
driver.get(url)
time.sleep(5)

tags = driver.find_elements_by_xpath('//div[@id="islrg"]/div[@class="islrc"]/div/a[1]')

for tag in tags:
    link = tag.get_attribute("href")
    print(link)

这将只打印无。

在页面源代码中,标签没有 href ,我只能从 inspect element 看到它。我怎样才能得到这些元素的href?

【问题讨论】:

    标签: python selenium


    【解决方案1】:

    错误原因;

    需要加载你想要的href

    from selenium import webdriver
    from time import sleep
    
    keyword = "cats"
    url = "https://www.google.com/search?q=" + keyword + "&source=lnms&tbm=isch&tbs="
    
    driver= webdriver.Chrome()
    driver.get(url)
    
    tags = driver.find_elements_by_xpath("//a[@class='wXeWr islib nfEiy mM5pbd']")
    
    for tag in tags:
        tag.click()
        sleep(1)
        print(tag.get_attribute('href'))
    

    解决方案;

    我点击“标签”安装href

    【讨论】:

    • 我的 xpath 是正确的,这些是我想要的元素。他们确实有一个 href 属性,但它只能从 inspect element 中看到,而不是从 page source 看到。我的问题是我怎样才能得到它。硒能做到这一点吗?
    • 你可以试一下代码,看看能不能得到你想要的输出吗?
    • 我不想要这些元素的 href。我想要 OP 中元素的 href。
    • 必须加载您想要的内容,所以在我看来,href 丢失了,我更正了您可以重试的代码
    猜你喜欢
    • 2021-09-12
    • 1970-01-01
    • 2017-08-18
    • 2018-01-04
    • 2018-08-14
    • 2013-05-05
    • 2013-02-23
    • 2022-12-12
    • 2013-04-07
    相关资源
    最近更新 更多