2015-12-12 1974 views
0

我需要從這個page中取消一些信息。用selenium和Python點擊'onclick'按鈕

但是,頁面在輸入之前需要進行年齡確認。它有一個按鈕,必須點擊才能看到頁面。我的問題是,我點擊這個按鈕的方法根本行不通。

我使用硒和Python 2.7.10。

這裏是我的代碼:

def download_specific_page(url): 
    try: 
     browser = get_browser() 
     wait = WebDriverWait(browser, 30) 
     browser.get(main_page_url) 
     time.sleep(2) 
     buttons = browser.find_elements_by_class('close') 
     for button in buttons: 
      onclick_text = button.get_attribute('onclick') 
      if onclick_text and re.search('ConfirmAge();', onclick_text): 
       print "found it!" 
       button.click() 
     browser.get(url) 
     html = browser.page_source 
     browser.close() 
     return html 
    except Exception: 
     info = 'Generic exception\n' 
     return "" 

我也嘗試過使用XPath,但還是沒有成功:

def download_specific_page(url): 
    try: 
     browser = get_browser() 
     wait = WebDriverWait(browser, 30) 
     browser.get(main_page_url) 
     button = browser.find_element_by_xpath("/html/body/div#bg_image/div.container/div#content/div#confirmage/div.confirmage_navigation/button.close[1]") 
     button.click() 
     time.sleep(2) 
     browser.get(url) 
     html = browser.page_source 
     browser.close() 
     return html 
    except Exception: 
     info = 'Generic exception\n' 
     return "" 

任何想法如何點擊這個按鈕,所以我就廢了頁面?

回答

2

使用常規點擊:

from selenium import webdriver 

URL = 'https://www.24dolores.pl/pl/ogloszenia-towarzyskie' 
CSS_SELECTOR = '.close' 

browser = webdriver.Chrome() 
browser.implicitly_wait(10) 
browser.get(URL) 
close = browser.find_element_by_css_selector(CSS_SELECTOR) 
close.click() 
+0

好的,謝謝你,它的工作:)終於來了! – darias

+0

不,我使用Firefox,但它的工作原理,謝謝:)(我犯了一個愚蠢的錯誤,我不使用Chromium;) – darias

+0

當我運行該示例時,我使用了Linux。現在在Windows上嘗試它,我得到消息'無法找到元素與CSS選擇'關閉' – darias