我如何使用 Selenium 在网页上指向这个独特的图像?
How can I point to this unique image on a webpage with Selenium?
我有一个包含大量图片的网站。我正在尝试获取网页上特定图像的“src”。但是我似乎无法找到一种方法来精确地只指向那个特定的图像。因为我知道的每一种可能的方式总是 returns 更多的结果。
如果你去:
https://weheartit.com/entry/349292873
你会看到一个最大的图像正直勾勾地盯着你。
当张贴者没有提供标题(我后来发现)时,它获得了“{user} 图片”的 alt 属性,因此我尝试使用 [contains(text(), 'Image by')]
标识符。如果用户实际提供标题,这显然不起作用。例如,在我上面列出的示例网页中,图像的替代值为 'aesthetic, couple, and cute image'。
所以我试图指向列出元素的树:
//div/div/a/img
其中returns同一棵树的5个不同结果。所以我尝试使用 nth:child 来代替:
"(//div/div/a/img)[4]"
在大多数页面上都有效,但在某些页面上它指向网站徽标而不是我要下载的图像,因为第 n 个结构已损坏并且第 4 个 child 突然变成了我想要的其他东西正在尝试下载。
这引出了我最初的问题。我怎样才能正确地仅指向我要下载的实际图像。我找不到这样做的方法,如果有人能帮我解决这个问题,我将不胜感激!
您正确地描述了问题。
所以,
1 等待此元素可见
2 通过get_attribute("src")
获取其属性
我用的是css定位器,不过用xpath也可以。
解决方案
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
driver = webdriver.Firefox()
driver.get('https://weheartit.com/entry/349292873')
wait = WebDriverWait(driver, 15)
wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, ".panel-large.list.js-entry-panel>a>img")))
link = driver.find_element_by_css_selector(".panel-large.list.js-entry-panel>a>img").get_attribute("src")
print(link)
driver.close()
driver.quit()
输出:
https://data.whicdn.com/images/349292873/original.gif
我有一个包含大量图片的网站。我正在尝试获取网页上特定图像的“src”。但是我似乎无法找到一种方法来精确地只指向那个特定的图像。因为我知道的每一种可能的方式总是 returns 更多的结果。
如果你去: https://weheartit.com/entry/349292873
你会看到一个最大的图像正直勾勾地盯着你。
当张贴者没有提供标题(我后来发现)时,它获得了“{user} 图片”的 alt 属性,因此我尝试使用 [contains(text(), 'Image by')]
标识符。如果用户实际提供标题,这显然不起作用。例如,在我上面列出的示例网页中,图像的替代值为 'aesthetic, couple, and cute image'。
所以我试图指向列出元素的树:
//div/div/a/img
其中returns同一棵树的5个不同结果。所以我尝试使用 nth:child 来代替:
"(//div/div/a/img)[4]"
在大多数页面上都有效,但在某些页面上它指向网站徽标而不是我要下载的图像,因为第 n 个结构已损坏并且第 4 个 child 突然变成了我想要的其他东西正在尝试下载。
这引出了我最初的问题。我怎样才能正确地仅指向我要下载的实际图像。我找不到这样做的方法,如果有人能帮我解决这个问题,我将不胜感激!
您正确地描述了问题。 所以,
1 等待此元素可见
2 通过get_attribute("src")
我用的是css定位器,不过用xpath也可以。
解决方案
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
driver = webdriver.Firefox()
driver.get('https://weheartit.com/entry/349292873')
wait = WebDriverWait(driver, 15)
wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, ".panel-large.list.js-entry-panel>a>img")))
link = driver.find_element_by_css_selector(".panel-large.list.js-entry-panel>a>img").get_attribute("src")
print(link)
driver.close()
driver.quit()
输出:
https://data.whicdn.com/images/349292873/original.gif