簡體   English   中英

Python中的Selenium:如果不存在鏈接,則不知道如何單擊下一頁

[英]Selenium in Python: Do not know how to click on next page if link is not present

嗨,我是python的新手,並且一直在進行網絡抓取。 這是我的代碼如下所示:

print('What is the term to be searched?') 

term = input()

browser = webdriver.Firefox(executable_path ='/usr/local/bin/geckodriver')
browser.get('https://google.com/search?q=' + term)

try:    
   link = browser.find_element_by_link_text("Hello")

# (I want to make it so the first page has no links of interest, so I can proceed to clicking the next page)    
except NoSuchElementException:    
   nextPage = browser.find_element_by_css_selector('Css of next page button)    
   nextPage.click()

因此,上面的代碼給了我錯誤,所以我嘗試僅取出'link = browser.find_element'並搜索該詞並由Css_selector轉到下一頁,但是出現了Traceback錯誤。

任何幫助,將不勝感激。 謝謝

這是代碼消息:

Traceback (most recent call last):
  File "/Users/shaun/Documents/Python/mwpractice.py", line 17, in <module>
    nextPage = browser.find_element_by_css_selector('''<span class="csb ch" style="background:url(/images/nav_logo242_hr.png) no-repeat;background-position:-74px 0;background-size:167px;width:20px"></span>''')
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 498, in find_element_by_css_selector
    return self.find_element(by=By.CSS_SELECTOR, value=css_selector)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 832, in find_element
    'value': value})['value']
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 297, in execute
    self.error_handler.check_response(response)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/selenium/webdriver/remote/errorhandler.py", line 194, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.InvalidSelectorException: Message: Given css selector expression "<span class="csb ch" style="background:url(/images/nav_logo242_hr.png) no-repeat;background-position:-74px 0;background-size:167px;width:20px"></span>" is invalid: InvalidSelectorError: '<span class="csb ch" style="background:url(/images/nav_logo242_hr.png) no-repeat;background-position:-74px 0;background-size:167px;width:20px"></span>' is not a valid selector: "<span class="csb ch" style="background:url(/images/nav_logo242_hr.png) no-repeat;background-position:-74px 0;background-size:167px;width:20px"></span>"

您必須更仔細地閱讀錯誤消息。

selenium.common.exceptions.InvalidSelectorException:消息:給定CSS選擇器表達式...”

這是一條非常明確的消息-您提供的CSS選擇器是錯誤的。

如果要單擊下一頁按鈕,可以使用xpath:

browser.find_element_by_xpath('//*[@id="pnnext"]/span[2]').click()

下一頁按鈕的正確CSS選擇器是:

#pnnext > span:nth-child(2)

暫無
暫無

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

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