python - 获取selenium web元素标签的href值

标签 python selenium xpath selenium-webdriver

我想获取标签链接的url。我已附加元素的类以在 python 中键入 selenium.webdriver.remote.webelement.WebElement:

elem = driver.find_elements_by_class_name("_5cq3")

html 是:

<div class="_5cq3" data-ft="{&quot;tn&quot;:&quot;E&quot;}">
    <a class="_4-eo" href="/9gag/photos/a.109041001839.105995.21785951839/10153954245456840/?type=1" rel="theater" ajaxify="/9gag/photos/a.109041001839.105995.21785951839/10153954245456840/?type=1&amp;src=https%3A%2F%2Fscontent.xx.fbcdn.net%2Fhphotos-xfp1%2Ft31.0-8%2F11894571_10153954245456840_9038620401603938613_o.jpg&amp;smallsrc=https%3A%2F%2Fscontent.xx.fbcdn.net%2Fhphotos-prn2%2Fv%2Ft1.0-9%2F11903991_10153954245456840_9038620401603938613_n.jpg%3Foh%3D0c837ce6b0498cd833f83cfbaeb577e7%26oe%3D567D8819&amp;size=651%2C1000&amp;fbid=10153954245456840&amp;player_origin=profile" style="width:256px;">
        <div class="uiScaledImageContainer _4-ep" style="width:256px;height:394px;" id="u_jsonp_2_r">
            <img class="scaledImageFitWidth img" src="https://fbcdn-photos-h-a.akamaihd.net/hphotos-ak-prn2/v/t1.0-0/s526x395/11903991_10153954245456840_9038620401603938613_n.jpg?oh=15f59e964665efe28943d12bd00cefd9&amp;oe=5667BDBA&amp;__gda__=1448928574_a7c6da855842af4c152c2fdf8096e1ef" alt="9GAG's photo." width="256" height="395">
        </div>
    </a>
</div>

我想要 a 标签的 href 值落在 _5cq3 类中。

最佳答案

为什么不直接做呢?

url = driver.find_element_by_class_name("_4-eo").get_attribute("href")

如果你首先需要 div 元素,你可以这样做:

divElement = driver.find_elements_by_class_name("_5cq3")
url = divElement.find_element_by_class_name("_4-eo").get_attribute("href")

或通过 xpath 的另一种方式(假设您的 5cq3 元素中只有一个链接元素:

url = driver.find_element_by_xpath("//div[@class='_5cq3']/a").get_attribute("href")

关于python - 获取selenium web元素标签的href值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32369147/

相关文章:

excel - VBA Selenium with Chrome - 将文件上传到网页

php - Xpath 和根据祖先的元素值有条件地选择后代

listview - 使用 selenium xpath 从 Android 应用程序的元素列表中查找 Web 元素的子元素

python - "Public"对象的属性及其值

python - 实现自定义 Python 身份验证处理程序

python - 在不引起监控错误的情况下重试队列中的任务

java - ScrollTo 返回并出错,即使在该位置该元素是可单击的

javascript - 如何在 Selenium C# 中切换 Chrome 上的标签页?

xpath - 如何在 import.io 中正确设置 xpath 以进行抓取

python - 使用 subprocess.check_output() 在 python 中搜索文件