我正在尝试使用 selenium 单击链接然后退出。我是编程新手,但我看过一些有关这方面的教程,但仍然无法点击进入页面。我的代码如下,任何帮助将不胜感激!当我只是想从有效的网站上提取建筑物名称时。我似乎无法弄清楚为什么这不会。
## LEED v3 2009 texas
driver.get("https://www.usgbc.org/projects/?Country=%5B%22United+States%22%5D&Rating+System=%5B%22New+Construction%22%5D&Rating+Version=%5B%22v2009%22%5D&Certification=%5B%22Platinum%22%5D&State=%5B%22Texas%22%5D")
#check this is the right website
#print(driver.title)
buildings = []
try:
project_profiles = driver.find_elements(By.CLASS_NAME, "grid-item--title")
for profile in project_profiles:
building_name = profile.text
buildings.append(building_name)
print(building_name)
#load building profile page
building_profile_link = driver.find_element(By.LINK_TEXT, building_name).click()
time.sleep(5)
driver.back()
except:
driver.quit()
我尝试仅使用字符串和变量名称,但都不起作用
有两件事你必须解决 首先是将 Find by Linktext 替换为 PARTIAL_LINK_TEXT
building_profile_link = driver.find_element(By.PARTIAL_LINK_TEXT, building_name)
第二个是,一旦您单击当前页面中的链接,转到下一页并返回,project_profiles 元素列表将变得过时,您将在单击时获得过时的元素引用,因此您应该再次找到该列表以避免这种情况
完整代码已修复
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
driver = webdriver.Chrome()
driver.get(
"https://www.usgbc.org/projects/?Country=%5B%22United+States%22%5D&Rating+System=%5B%22New+Construction%22%5D&Rating+Version=%5B%22v2009%22%5D&Certification=%5B%22Platinum%22%5D&State=%5B%22Texas%22%5D")
# check this is the right website
# print(driver.title)
buildings = []
try:
project_profiles = driver.find_elements(By.CLASS_NAME, "grid-item--title")
for i in range(len(project_profiles)):
# Wait for page to load as order of elements will be incorrect otherwise
time.sleep(5)
project_profiles = driver.find_elements(By.CLASS_NAME, "grid-item--title") # Find the list again
building_name = project_profiles[i].text
buildings.append(building_name)
print(building_name)
# load building profile page
building_profile_link = driver.find_element(By.XPATH, f"//div[@id='result-grid']//h1[text()='{building_name}']")
building_profile_link.click()
time.sleep(5)
driver.back()
except Exception as e:
print(e)
driver.quit()
pip3安装ls5 pypi包,查看代码,你会找到你需要的。