python - 无法区分用于执行一项特定操作的两个选择器

标签 python python-3.x selenium web-scraping css-selectors

我用 python 结合 selenium 编写了一个脚本,用于单击网页中名为 follow 的按钮。问题是,当我尝试使用两个不同的选择器时,它们都可以单击同一个按钮。

第一个选择器:

"a[href$='/follow']"

第二个:

"a[href$='/follow'] > button"

相关html部分:

<div class="nZSzR">
    <h1 class="fDxYl">
        some royal personality
    </h1>
    <span class="VerifiedBadge" title="Verified">
        Verified
    </span>
    <a class="BY3EC" href="/accounts/follow" rel="nofollow">
        <button class="L3NKy" type="button">
            Follow
        </button>
    </a>
</div>

我应该坚持哪种方式,为什么?

最佳答案

米修,

您拥有的css选择器a[href$='/follow'],用href<表示 anchor 标记/follow 结尾的/strong> 属性

第二个 a[href$='/follow'] > 按钮 ,定位父级为 anchor 标记的按钮

因此,您可以在第二个 css 中清楚地看到,存在按钮的依赖关系。因此,如果您可以先进行,那么您应该优先考虑它。

对于这个HTML:

<a class="BY3EC" href="/accounts/follow" rel="nofollow">
        <button class="L3NKy" type="button">
            Follow
        </button>
</a>

显然第一个 css 的依赖性较小。

如果它是 anchor 标记,那么答案就不需要css选择器

您可以直接使用LINK_TEXTPARTIAL_LINK_TEXT

示例代码:

continue_link = driver.find_element_by_link_text('Continue')
continue_link = driver.find_element_by_partial_link_text('Conti')

欲了解更多信息,请访问此官方 link .

关于python - 无法区分用于执行一项特定操作的两个选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56600815/

相关文章:

java - 等待模式在 Selenium 2.0 中消失

python - 用于解析包含 'v.' 的标题的 pyparsing 语法

python - ipython 安装新模块

python - 如何在使用 nltk 使用 sent_tokenize 时从输出屏幕中删除\n

python-3.x - 在 Python3/tkinter 中如何设置框架相对于其父窗口大小的大小?

python - 如何根据预定义列表排列set的输出

python - 为什么用Selenium打开Firefox时,Firefox的url地址栏这么小?

php - Selenium 服务器 - 为正在测试的应用程序预定义常量?

python - 在python中获得一个范围的所有排列而无需连续邻居的最快方法

Python Requests/BeautifulSoup 访问分页