我是一名学生,正在使用python上的硒进行抓取项目。我正在尝试从多个格式相同的多个配置文件中抓取数据。有一个目录网站,带有指向所有配置文件的按钮,但是我遇到的问题是一次可以单击每个按钮,因为它们的格式都相同。我的目标是能够在新选项卡中打开第一个链接,从该配置文件中抓取数据,然后关闭第一个配置文件的选项卡,然后再移至第二个。我希望这个过程可以重复。这是我到目前为止的内容:
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
import time
from selenium.webdriver.common.keys import Keys
driver = webdriver.Chrome(executable_path="MY PATH TO MY CHROME DRIVER")
driver.implicitly_wait(5)
driver.get("http://directory.bcsp.org")
buttons = driver.find_elements_by_link_text('View Profile')
如果您有解决我问题的方法,请告诉我。谢谢:)
答案 0 :(得分:0)
“正文”以进入页面
“ profile_count”以获取链接
“。get_attribute('href')”,用于从“查看个人资料”按钮中抓取链接
“ temp”旧窗口中的信息不会切换到新窗口,因此我们需要temp
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from time import sleep
driver = webdriver.Edge()
driver.get("https://directory.bcsp.org/")
count = int(input("Count : "))
body = driver.find_element_by_xpath("//body") #
profile_count = driver.find_elements_by_xpath("//div[@align='right']/a")
while len(profile_count) < count: # Get links up to "count"
body.send_keys(Keys.END)
sleep(1)
profile_count = driver.find_elements_by_xpath("//div[@align='right']/a")
for link in profile_count: # Calling up links
temp = link.get_attribute('href') # temp for
driver.execute_script("window.open('');") # open new tab
driver.switch_to.window(driver.window_handles[1]) # focus new tab
driver.get(temp)
# you can do
# what you want
# to do here
driver.close()
driver.switch_to.window(driver.window_handles[0])
driver.close()