2017-06-13 58 views
0

我想在Python中使用Selenium,我試圖在bigkinds.or.kr上通過點擊增加的數字按鈕來循環訪問頁面。Python with Selenium:分頁問題

下一頁是根據Chrome檢查位於以下HTML:

<div class="newsPage"> 
    <div class="btmDelBtn"> 
          ...</div> 
<span> 
<a href="javascript:void(0);" class="current">1</a> 
<a href="javascript:void(0);" onclick="getSearchResultNew(2)">2</a> 
<a href="javascript:void(0);" onclick="getSearchResultNew(3)">3</a> 
<a href="javascript:void(0);" onclick="getSearchResultNew(4)">4</a> 
<a href="javascript:void(0);" onclick="getSearchResultNew(5)">5</a> 
<a href="javascript:void(0);" onclick="getSearchResultNew(6)">6</a> 
</span> 

我不是通過點擊下頁爬行獲得成功。請幫幫我。 這是我的代碼:

url = "https://www.bigkinds.or.kr/main.do" 
browser.get(url) 

... 

currentPageElement = browser.find_element_by_xpath("//*[@id='content']/div/div/div[2]/div[7]/span/a[2]") 

print(currentPageElement) 

currentPageNumber = int(currentPageElement.text) 

print(currentPageNumber) 

在XPath中, 「/跨度/ A []」 是一個頁號。我怎樣才能使這個xpath循環。

+0

1.您試圖元素的文本轉換爲整數:INT(currentPageElement.text )。 2.即使問題是關於單擊,您從不在代碼中的任何位置調用'click()'方法。 –

+0

在xpath中,「/ span/a [2]」是一個頁碼。我怎樣才能使這個xpath循環。 – wooah

回答

0

嘗試使用下面的代碼:

from selenium.common.exceptions import NoSuchElementException 

url = "https://www.bigkinds.or.kr/main.do" 
browser.get(url) 
page_count = 1 
while True: 
    # Increase page_count value on each iteration on +1 
    page_count += 1 
    # Do what you need to do on each page 
    # Code goes here 
    try: 
     # Clicking on "2" on pagination on first iteration, "3" on second... 
     browser.find_element_by_link_text(str(page_count)).click() 
    except NoSuchElementException: 
     # Stop loop if no more page available 
     break 

更新

如果你仍然想通過XPath使用搜索,你可能需要用線

更換線

browser.find_element_by_link_text(str(page_count)).click() 

browser.find_element_by_xpath('//a[@onclick="getSearchResultNew(%s)"]' % page_count).click() 

...或者,如果你想用你的絕對XPath(不是最好的主意),你可以嘗試

browser.find_element_by_xpath("//*[@id='content']/div/div/di‌​v[2]/div[7]/span/a[%s​]" % page_count).click() 
+0

謝謝。但我想知道xpath中增加的數字。 currentPageElement = browser.find_element_by_xpath(「// * [@ id ='content']/div/div/div [2]/div [7]/span/a [** 2 **]」) – wooah

+0

檢查更新回答 – Andersson

+0

非常感謝。有用!! ^^ – wooah