【问题标题】:Clicking on Links With Variable IDs in Python / Selenium在 Python / Selenium 中单击具有变量 ID 的链接
【发布时间】:2019-09-23 18:53:40
【问题描述】:

我正在抓取大学招生系统的网站。每个页面链接到许多其他页面。每个链接的 ID 为 SEC_SHORT_TITLE_x,其中 x 是 1-20 的整数。在每个页面上,我想抓取一些数据。现在我只是想刮掉部分名称。将处理返回页面并在此之后单击下一个链接的逻辑。

DevTools 显示 xPath:

for y in range(1):
    for j in range(1,2):
        if browser.find_elements_by_xpath("//a[@id='SEC_SHORT_TITLE_" + str(j) + "']"):
            #outputstring = ''
            browser.find_elements_by_xpath("//a[@id='SEC_SHORT_TITLE_" + str(j) + "']").click()
            time.sleep(10)
            section = browser.find_elements_by_xpath("//p[@id='VAR2']")
            print(section)

脚本导航到包含所有链接的正确页面,但无法正常点击第一个链接。

[7756:2296:0923/141749.015:ERROR:ssl_client_socket_impl.cc(941)] handshake failed; returned -1, SSL error code 1, net_error -100

【问题讨论】:

  • this discussion 对您有帮助吗?
  • 是的,这解释了问题 - 谢谢@DebanjanB

标签: python selenium


【解决方案1】:

根据您提供的错误消息 (SyntaxError: Failed to execute 'evaluate' on 'Document': The string '//a[@id='SEC_SHORT_TITLE_1]' is not a valid XPath expression. (Session info: chrome=77.0.3865.90)),您的 XPath 语法似乎不正确。您需要在方括号内添加一个结束标记。

更改//a[@id='SEC_SHORT_TITLE_1]

//a[@id='SEC_SHORT_TITLE_1']

注意我是如何在 'SEC_SHORT_TITLE_1' 之后添加一个 ' 标记的。

根据您的代码示例,您需要通过更改来更新此行:

browser.find_elements_by_xpath("//a[@id='SEC_SHORT_TITLE_" + str(j) + "]"):

到:

browser.find_elements_by_xpath("//a[@id='SEC_SHORT_TITLE_" + str(j) + "']"):

我在右方括号前添加了一个 ' 标记以更正 XPath 语法。

【讨论】:

  • 抱歉,我必须发布一条较旧的错误消息,因为我已经修复了该问题。将重新运行并发布新的错误消息。感谢回复
  • 没问题,让我知道你发现了什么。乐于助人。
  • @Sartorialist 这可能与需要 SSL 的网站有关。您可以尝试通过在初始化 WebDriver 时将 --ignore-certificate-errors 和 --ignore-ssl-errors 添加到 ChromeOptions() 来绕过此问题。更多信息可以在这里找到stackoverflow.com/questions/37883759/…
猜你喜欢
  • 2015-05-29
  • 1970-01-01
  • 2014-11-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多