[英]Can't make hidden part of a web page active using selenium in python
I'm trying to use selenium in python to extract data from AllTrails.com/us/florida/state-parks.我正在尝试在 python 中使用 selenium 从 AllTrails.com/us/florida/state-parks 中提取数据。 What I need is the recordings data.
我需要的是录音数据。 The site looks like the picture below when you first open it, with "reviews" active.
当您第一次打开该网站时,该网站如下图所示,其中“评论”处于活动状态。
The html code for the portion of interest is:感兴趣部分的 html 代码为:
Right now you can see in the html that 'reviews' is active (I need recordings active)现在您可以在 html 中看到“评论”处于活动状态(我需要录音处于活动状态)
When I physically click on the "recordings" it activates recordings, but when I try to virtually "click" on it with selenium, it does not give an error, but it is not activated and subsequent parts of the code then will not work.当我物理单击“录音”时,它会激活录音,但是当我尝试使用 selenium 虚拟“单击”它时,它不会给出错误,但它没有被激活,并且代码的后续部分将不起作用。 The relevant portion of my code is below:
我的代码的相关部分如下:
def get_trail_links (driver, trails_url):
time.sleep(1)
driver.get(trails_url)
page_count = 0
#here is where i am trying to click on the "recordings" button, no error happens here.
driver.find_element_by_xpath("//h3[a/@name='Recordings']").click()
recordings = driver.find_elements_by_xpath("//*[@id ='tracks']")
while page_count < 2:
for record in recordings:
#here is where my button won't work because the recordings is not active in the html.
button = driver.find_element_by_xpath("//button[@title='Show more recordings']")
button.click()
time.sleep(1)
page_count += 1
Use this code.使用此代码。 Also you can change the number of times the button click by changing the value in the while loop.
您还可以通过更改 while 循环中的值来更改按钮单击的次数。
import time
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
driver = webdriver.Chrome(executable_path= r"D:\Selenium Learning\chromedriver_win32 (2)\chromedriver.exe")
driver.get('https://www.alltrails.com/us/florida/state-parks')
wait = WebDriverWait(driver, 5000)
wait.until(EC.element_to_be_clickable((By.XPATH, "//div[contains(@class,'row trail-row')]/div/div[3]")))
driver.find_element_by_xpath("//div[contains(@class,'row trail-row')]/div/div[3]").click()
wait.until(EC.element_to_be_clickable((By.XPATH, "//*[@id='tracks']/div[1]/div[1]/div[2]/div[1]/div[1]/h4")))
page_count=0
while page_count < 2:
button = driver.find_element_by_xpath("//button[@title='Show more recordings']")
button.click()
time.sleep(1)
page_count += 1
recordings = driver.find_elements_by_xpath("//*[@id='tracks']/div/div/div/div/div/h4")
for recording in recordings:
print(recording.text)
PS: While executing please change the executable path to your local chrome driver path. PS:执行时请将可执行路径更改为您本地的chrome驱动程序路径。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.