【问题标题】:How to extract background-image URL from div style selenium/python?如何从 div 样式 selenium/python 中提取背景图像 URL?
【发布时间】:2020-10-02 19:03:44
【问题描述】:
<div style="left: 0%;background-image: url(&quot;https://i.xxxx.com/pictures/3724063802.jpg?type=original&quot;);width: 100%;height: 100%;background-size: contain;background-position: 50% 50%;background-repeat: no-repeat;position: absolute;"></div>

如何使用 Python 从 selenium 中的上述 html 中定位和提取背景图像 URL? 我的问题是我之前用过id,没有id怎么办?

【问题讨论】:

  • 使用 css_selector。右键单击元素并检查并复制选择器。然后解析它。

标签: python css selenium


【解决方案1】:

我建议使用 XPath 来查找 div (find_element_by_xpath("//div")),您可以通过索引找到您正在寻找的特定 div 元素(//div[3]//div[0] 等)

要提取背景图像,请使用value_of_css_property() 方法。

bg_url = div.value_of_css_property('background-image') # 'url("https://i.xxxx.com/img.jpg")'
# strip the string to leave just the URL part
bg_url = bg_url.lstrip('url("').rstrip('")')
# https://i.xxxx.com/img.jpg

另一种方法是使用find_elements_by_tag_name('div'),因为这将返回一个 div 列表,但您必须筛选它们才能找到您想要的。

【讨论】:

  • 谢谢!刚刚复制了Xpath: div = driver.find_element_by_xpath(//*[@id='abc-asd']/div[2]/div[2]...) 然后取css属性的值:bg_url = div。 value_of_css_property('background-image') 并剥离它!非常感谢您的帮助!
  • 随时!很高兴我能帮忙:)
猜你喜欢
  • 1970-01-01
  • 2014-01-18
  • 1970-01-01
  • 1970-01-01
  • 2023-04-01
  • 1970-01-01
  • 2020-03-20
  • 2019-02-19
  • 2018-02-26
相关资源
最近更新 更多