[英]Python Selenium unable to click() button
我正在嘗試從這里自動抓取鏈接:
獲得第一頁后,我想單擊底部右側的 V 形圖標,以便移動到第二頁、第三頁,依此類推。 刮掉兩者之間的鏈接。
不幸的是,我嘗試的任何內容都不允許我將 chrome 發送到下一頁。
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
from datetime import datetime
import csv
from selenium.webdriver.common.action_chains import ActionChains
#User login info
pagenum = 1
#Creates link to Chrome Driver and shortens this to 'browser'
path_to_chromedriver = '/Users/abc/Downloads/chromedriver 2' # change path as needed
driver = webdriver.Chrome(executable_path = path_to_chromedriver)
#Navigates Chrome to the specified page
url = 'https://thegoodpubguide.co.uk/pubs/?paged=1&order_by=category&search=pubs&pub_name=&postal_code=®ion=london'
#Clicks Login
def findlinks(address):
global pagenum
list = []
driver.get(address)
#wait
while pagenum <= 2:
for i in range(20): # Scrapes available links
xref = '//*[@id="search-results"]/div[1]/div[' + str(i+1) + ']/div/div/div[2]/div[1]/p/a'
link = driver.find_element_by_xpath(xref).get_attribute('href')
print(link)
list.append(link)
with open("links.csv", "a") as fp: # Saves list to file
wr = csv.writer(fp, dialect='excel')
wr.writerow(list)
print(pagenum)
pagenum = pagenum + 1
element = driver.find_element_by_xpath('//*[@id="search-results"]/div[2]/div/div/ul/li[8]/a')
element.click()
findlinks(url)
是不是有什么東西擋住了我沒有看到的按鈕?
我的終端中打印的錯誤:
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="search-results"]/div[2]/div/div/ul/li[8]/a"}
嘗試這個 :
element = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "a[class='next-page btn']"))
element.click()
您為 V 形指定的 xpath 在頁面之間是可變的,並且不完全正確。 注意li[6]
和li[8]
和li[9]
。
在第 1 頁:xpath 是//*[@id="search-results"]/div[2]/div/div/ul/li[6]/a/i
在第 2 頁:xpath 是//*[@id="search-results"]/div[2]/div/div/ul/li[8]/a/i
在第 3 頁:xpath 是//*[@id="search-results"]/div[2]/div/div/ul/li[9]/a/i
您必須想出某種方法來確定要使用的 xpath。 這里有一個提示:似乎//*[@id="search-results"]/div[2]/div/div/ul/
下的最后一個li
指定了 V 形。
您可能想嘗試等待頁面加載,然后再嘗試查找並單擊 V 形圖標。 當我測試我的自動化腳本時,我通常只做一個time.sleep(...)
,但對於(可能)更復雜的功能,請嘗試Waits
。 請參閱此處的文檔。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.