繁体   English   中英

使用Python在Selenium中使用find_elements_by_class_name查找href属性

[英]Find href attributes with find_elements_by_class_name in Selenium with Python

在Python中使用Selenium。

我的页面充满了名为item-title的类的链接。 我试图遍历页面并编译所有链接文本和它们所伴随的href属性的列表。 我想输出标题和指向csv文件的链接。 这是我的代码:

myLinks=driver.find_elements_by_class_name("item-title")
for link in myLinks:
    out.write(link.text)
    out.write (",") 
    out.write(link.get_attribute("href"))
    out.write("\n")

输出href值的行出现以下错误:

TypeError:预期的字符缓冲区对象

尝试了以下内容:

myLinks=driver.find_elements_by_class_name("item-title")
for link in myLinks:
    out.write(link.text)
    out.write (",") 
    out.write(str(link.get_attribute("href")))
    out.write("\n")

错误消失了,链接文本通过了,但是现在href通过“ None”通过了

编辑以添加HTML

<div class="item-title">
    <span class="icons-pinned"></span>
    <span class="icons-solved"></span>
    <span class="icons-locked"></span>
    <span class="icons-moved"></span>
    <span class="icons-type"></span>
    <span class="icons-reply"></span>
    <a href="/mylink">My title</a>
</div>

我想我现在看到了这个问题。 是div的子元素,我需要定位该对象,不是吗?

根据您共享的HTML, link textshref attributes不在标识为find_elements_by_class_name("item-title")的节点内。 而是它们位于下降的<a>标记内。 因此,必须使用find_elements_by_xpathfind_elements_by_css_selector来代替使用find_elements_by_class_name("item-title")

  • 使用find_elements_by_css_selector

     myLinks=driver.find_elements_by_css_selector("div.item-title > a") for link in myLinks: out.write(link.get_attribute("innerHTML")) out.write (",") out.write(link.get_attribute("href")) out.write("\\n") 
  • 使用find_elements_by_xpath

     myLinks=driver.find_elements_by_xpath("//div[@class='item-title']/a") for link in myLinks: out.write(link.get_attribute("innerHTML")) out.write (",") out.write(link.get_attribute("href")) out.write("\\n") 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM