【问题标题】:selenium can't recognize href hypertextselenium 无法识别 href 超文本
【发布时间】:2017-10-10 23:58:56
【问题描述】:

我正在尝试使用 selenium 单击网页源中的一些链接。这是我到目前为止得到的:

import selenium, time
import html5lib
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
pg_src = br.page_source.encode("utf")
soup = BeautifulSoup(pg_src)
br = webdriver.Chrome()

url = "http://somewikipage.org"

br.get(url)

lnkLst = soup.find_all("a", href=re.compile(",_California") # this builds a list with everything in the a href tag

nuLst = []

for i in lnkLst:

    nuLst.append(i.get('href')) #this removes all the unclickable text from the a href tag

for i in nuLst:

    br.find_element_by_link_text(i).click()

这会导致以下错误:

AttributeError: 'list' object has no attribute 'click'

我已经打印出 nuLst 并且每个项目都与 href 标记中的超链接完全匹配。在使用 find_element_by_xpath 之前我做了类似的事情,但我不确定如何在不调用页面上所有其他 href 的情况下隔离这组 href 的 css 选择器。

【问题讨论】:

  • 我认为错误来自:br.find_element_by_link_text(i),参数:i 是链接的 url,而不是链接的文本。所以你应该将链接文本附加到 nuLst 而不是 href 处: nuLst.append(i.get('href'))

标签: python selenium beautifulsoup


【解决方案1】:

AttributeError: 'list' 对象没有属性 'click'

您正在尝试单击对象列表(没有单击方法),而不是单击 Web 元素列表中的 Web 元素。

首先获取所有链接的web元素列表

list = driver.find_elements_by_xpath("//a")//Note, there is 'elements' not element

现在根据您的要求遍历此列表。

【讨论】:

  • 我使用您的代码获得了元素列表,但点击操作仍然无效。我最终使用了一个 for 循环并从可迭代对象中构建了一个 url,然后使用了 br.get(url)。这让我得到了我需要的东西。
  • 太好了。您可以编辑我上述答案中的内容并将其标记为正确,以便对其他人有所帮助。
猜你喜欢
  • 2016-04-14
  • 2021-12-08
  • 1970-01-01
  • 1970-01-01
  • 2017-05-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多