如何使用Selenium单击链接

时间:2018-02-08 08:51:11

标签: python selenium-webdriver

我想点击使用Selenium和Python的链接。以下html代码中的文本为“104”:

let task2 = URLSession.shared.dataTask(with: request2 as URLRequest) {(data2, response2, error2) -> Void in
    if let unwrappedData2 = data2 {
        do {
            guard let records = try? JSONSerialization.jsonObject(with: unwrappedData2, options: .mutableContainers) as? [[String: Any]] else {
                print("[DEBUG] - Unable to parse JSON as array")
                return
            }

            let firstRecord = records.first
            print(records.count, firstRecord)

        } catch {}
    }
}

我试过

<a class="_2x4v" href="/ufi/reaction/profile/browser/?ft_ent_identifier=2411812215520941&amp;av=200007162833925" rel="ignore" role="button">1045
  <span aria-hidden="true" class="_1g5v">
    <span data-hover="tooltip" data-tooltip-uri="/ufi/reaction/tooltip/?ft_ent_identifier=2411812215520941&amp;av=200007162833925">104</span>
  </span>
  <span class="_4arz">
    <span data-hover="tooltip" data-tooltip-uri="/ufi/reaction/tooltip/?ft_ent_identifier=2411812215520941&amp;av=200007162833925">104</span>
  </span>
</a>

但我收到了一个错误:

driver.find_element_by_xpath('//a[text()="104"]').click()

我该怎么办?

1 个答案:

答案 0 :(得分:2)

链接没有子文本节点"104" - 它是span的子文本节点。您可以尝试以下选项来匹配所需的链接:

//a[span="104"]

//a[.//text()="104"]

//a[.//span[text()="104"]]

...