【问题标题】:How can these javascript links be traversed with Selenium or BeautifulSoup?Selenium 或 BeautifulSoup 如何遍历这些 javascript 链接?
【发布时间】:2016-10-12 01:10:24
【问题描述】:

我选择了 Selenium,因为链接的 href 是动态生成的,尽管通过 bs4 的一些方法会更好。

我正在使用 PhantomJS,但也尝试过 Firefox

当试图点击一个链接时,什么也没有发生。

例如,

url = 'http://www.achema.de/de/ausstellung/aussteller-und-produkte.html'

driver.get(url)

resultsBox = driver.find_element_by_css_selector('div[id="ix_result"]')

for tr in resultsBox.find_elements_by_tag_name('tr'):
    link = tr.find_element_by_tag_name('a')
    link.click()

    # I've also tried:
    # ActionChains(driver).move_to_element(link).click(link).perform()

【问题讨论】:

  • 你确定你正在迭代的集合有元素'a'吗?您应该提供测试输入以获得更好的答案。

标签: python selenium beautifulsoup


【解决方案1】:

正如 Orenthal 所说,我发现该链接被点击了。但是,要加载的页面是完全动态的,因此在尝试从该链接中提取之前至少需要休眠 2 秒。

【讨论】:

  • 我最近第一次涉足 selenium 时遇到了同样的问题,我在测试中使用了 time.sleep(5),但没有它也可以工作,但这可能取决于机器/浏览器/连接。
【解决方案2】:

我不太确定我知道您要单击的内容,但我使用以下代码单击了“Agora Pavillon C7”页面上的第一个列表。

from selenium import webdriver

def so_test():

    driver = webdriver.Firefox()

    def connect():
        driver.get('http://www.achema.de/de/ausstellung/aussteller-und-produkte.html')
        div = driver.find_element_by_id('ix_result_aussteller')
        test_link = div.find_elements_by_tag_name('tr')
        link = test_link[0].find_element_by_tag_name('a')
        link.click()

    connect()

so_test()

如果您尝试点击上面的导航链接,正确的目标应该是:

from selenium import webdriver

def so_test():

    driver = webdriver.Firefox()

    def connect():
        driver.get('http://www.achema.de/de/ausstellung/aussteller-und-produkte.html')
        div = driver.find_element_by_id('ix_letters')
        test_link = div.find_elements_by_tag_name('li')
        link = test_link[0].find_element_by_tag_name('a')
        link.click()

    connect()

so_test()

类似的东西。如果我不在基地,请告诉我。我很乐意尝试并提供更多帮助。

【讨论】:

  • 感谢您的回复。我发现链接被点击了,但要加载的页面是完全动态的,因此在尝试从该链接中提取之前需要至少 2 秒的睡眠
  • from selenium import webdriver 不是第二个代码块的一部分,这有点烦人。而且我什至不能提交编辑,因为这是这个答案中唯一的错误。 :D
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-10-01
  • 2013-04-27
  • 1970-01-01
  • 2016-06-29
  • 2020-11-03
  • 2019-12-31
  • 1970-01-01
相关资源
最近更新 更多