使用硒抓取链接(href)的问题; href="#"

时间:2021-01-06 07:21:47

标签: python selenium href

我是使用 python 的业余爱好者,我正在尝试使用 selenium 从下面的 html 中抓取 url。

<a class="" href="#" style="text-decoration: none; color: #1b1b1b;" onclick="toDetailOrUrl(event, '1641438','')">[안내] 빗썸 - 빗썸 글로벌 간 간편 가상자산 이동 서비스 종료 안내</a>

通常情况下,我想要获取的链接 url 就在 'href=' 旁边,但该 html 中只有“#”。

当我运行下面的代码时,这是使用 selenium 抓取给定 html 的常用方法,它返回一个 https://cafe.bithumb.com/view/boards/43。但这正是我在“driver.get()”中输入的内容,我不想要。

   url = "https://cafe.bithumb.com/view/boards/43"
    driver=webdriver.Chrome('chromedriver.exe')
    driver.get(url)
    driver.implicitly_wait(30)
    bo =driver.find_element_by_xpath("//tbody[1]/tr[@style='cursor:pointer;border-top:1px solid #dee2e6;background-color: white']/td[2]/a")
    print(bo.get_attribute('href'))

我想要的是https://cafe.bithumb.com/view/board-contents/1641438。当您单击与我上面写的 xpath 对应的项目时,您可以获取此 url。

我想要这个 url 使用 selenium 或其他编程方式,不需要打开 chrome 并在地址栏中输入 url,然后使用鼠标点击......就像那样。

2 个答案:

答案 0 :(得分:0)

你可以使用,

bo.click()

为了点击你想要的元素(我假设你想点击 bo)

答案 1 :(得分:0)

print(driver.execute_script('return arguments[0].getAttribute("href")',bo))

selenium , bo.get_attribute('href') 实际上是在做 document.getElementById("somelocaator").href ,它返回完整的 href ,因为 '#' 表示当前页面你得到你在 get() 中提供的当前 URL

如果你只需要#你可以使用execute_script