簡體   English   中英

Python,Selenium,BS4-導航到下一頁

[英]Python, Selenium, BS4 - Navigating to the next Page

我的HTML的一部分如下所示:

<div id="qryNav">
<form method="post" action="OffQryRedirector.jsp" id="form1" name="form1">
    <input type="hidden" name="NextPage" value="7" />
    <input type="submit" name="Action" id="oq-nav-begin" value="&lt;&lt;" />
    <input type="submit" name="Action" id="oq-nav-prv" value="&lt;" />
<span class="oq-nav-btwn">Page 1 of 4</span>
    <input type="submit" name="Action" id="oq-nav-nxt" value="&gt;" />
    <input type="submit" name="Action" id="oq-nav-end" value="&gt;&gt;" />  
</form>
<a href="OffQryForm.jsp" class="qryNav"><span>Start a New Search</span></a> 
<!--<a href="javascript:history.back()" class="qryNav"><span>Modify Your Search</span>    </a>--> 
</div>

我正在嘗試確定頁數,然后移至下一頁。 我的代碼如下所示-

html = driver.page_source
soup = BeautifulSoup(html)
pages =  soup.find_all('span', {'class': 'oq-nav-btwn'})[0].text.encode('ascii',     'ignore').strip().upper()
loc_of = pages.find('OF')
num_pages = int(pages[loc_of+2:].strip())
>>> print num_pages
4
span = soup.find_all('span', {'class': 'oq-nav-btwn'})
elem2 = span[0].find_next_sibling() 
elem2.find_element_by_id("oq-nav-nxt")

發布此信息,我嘗試為4頁中的每一個運行循環-1.。4.但是,當我使用

elem2.find_element_by_id("oq-nav-nxt").click()

我得到了標准的selenium.common.exceptions.StaleElementReferenceException:消息:u'stale元素引用:元素未附加到頁面文檔\\ n(會話信息:chrome = 34.0.1847.131)\\ n(驅動程序信息:chromedriver = 2.9。 248315,platform = Windows NT 6.1 x86_64)'

該元素是可見的。 我不認為try..catch ... wait ..是解決此問題的方法..(我在這里可能錯了。)

我也嘗試使用下面的代碼做同樣的事情-

span = soup.find_all('span', {'class': 'oq-nav-btwn'})
elem2 = span[0].find_next_sibling()
>>> print elem2
<input id="oq-nav-nxt" name="Action" type="submit" value="&gt;">
<input id="oq-nav-end" name="Action" type="submit" value="&gt;&gt;">
</input></input>

但是我無法瀏覽上面的elem2值,然后單擊“ oq-nav-nxt”按鈕。

感謝您的幫助。

您無需在此處使用BeautifulSoup Selenium元素定位方面非常強大。

一種選擇是繼續通過id查找下一頁鏈接直到找不到為止:

while True:
    try:
        next_button = driver.find_element_by_id('oq-nav-nxt')
    except NoSuchElementException:
        break
    next_button.click()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM