python - 我想使用 selenium 和 python 打开网站中的每个项目进行抓取

标签 python selenium-chromedriver

我正在尝试打开一个网站进行抓取,即在打开一个产品的新选项卡后,它应该抓取,然后返回到原始选项卡,然后返回其他产品。 我认为问题出在 Xpath 上,我使用了 xpath "//a[contains(@class,'prdLink')]"

这里我使用了xpath方法,但不知何故它没有打开页面

  chromeOptions = webdriver.ChromeOptions()
    chromeOptions.add_experimental_option('useAutomationExtension', False)
    driver = webdriver.Chrome(executable_path='C:/Users/ptiwar34/Documents/chromedriver.exe', chrome_options=chromeOptions, desired_capabilities=chromeOptions.to_capabilities())
    
    while True:
        try:
            driver.get("https://www.besse.com/pages/products-specialties/productsbyspecialty/allspecialties")
            my_hrefs = [my_elem.get_attribute("href") for my_elem in WebDriverWait(driver, 10).until(EC.visibility_of_all_elements_located((By.XPATH, "//a[contains(@class,'prdLink')]")))]
            windows_before  = driver.current_window_handle 
            for my_href in my_hrefs:
                driver.execute_script("window.open('" + my_href +"');")
                WebDriverWait(driver, 10).until(EC.number_of_windows_to_be(2)) 
                windows_after = driver.window_handles
                new_window = [x for x in windows_after if x != windows_before][0] 
                driver.switch_to.window(new_window) 
                time.sleep(3) 
                print(driver.title) 
                driver.close() 
                driver.switch_to.window(windows_before) 
        except TimeoutException:
            print("No more pages")
            break
    driver.quit()

它甚至无法打开单个项目,并且输出不再是页面

最佳答案

xpath 是正确的,问题是这些链接不可见。您需要扩展所有部分(并且您需要使用向下滚动来实现这一点)。

在这种情况下,更快的方法是解析页面源,而不是在此处使用 selenium。

from lxml import etree

driver.get("https://www.besse.com/pages/products-specialties/productsbyspecialty/allspecialties")

root = etree.HTML(driver.page_source)

# there is @href!='' in xpath because some hrefs contains empty string
my_hrefs = root.xpath(".//a[contains(@class,'prdLink') and @href!='']/@href")
for my_href in my_hrefs:
    # rest of your code

关于python - 我想使用 selenium 和 python 打开网站中的每个项目进行抓取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57648511/

相关文章:

android - Watir-Webdriver 在 Android 设备上控制 Android ChromeDriver

java - 我需要添加一个等待,直到我得到来自带有 selenium-java 的 Angular http 请求的响应

android - 使用机器人框架脚本和 chromedriver 在 Android 设备中打开 Chrome 浏览器?

python - 返回语句不返回电子邮件的值

python - pydev 无法识别 django 安装

python - Scrapy 图像管道警告 : File (unknown-error): Error downloading image from <GET

python - 使用 "OR"组合多个 Selenium 等待?

python - 将 `sqlachemy` 连接到 django 数据库

python - 如何检查字典中的两个键是否具有相同的值

python - 操作系统错误 : [Errno 8] Exec format error: 'chromedriver' using Chromedriver on Ubuntu server