[英]How to open each product within a website in a new tab for scraping using Selenium through Python
[英]Selenium Python, parsing through website, opening a new tab, and scraping
我是 Python 和 Selenium 的新手。 我正在嘗試做一些事情——我確信我會以一種非常迂回的方式進行——任何幫助都非常感謝。
我試圖解析的頁面有不同的卡片需要點擊,我需要轉到每張卡片,然后從那里獲取名稱 (h1) 和 url。 我還沒有走得很遠,這就是我到目前為止所擁有的。
我瀏覽第一頁,獲取所有網址,將它們添加到列表中。 然后我想瀏覽列表,並轉到每個 url(打開一個新選項卡)並從那里獲取 h1 和 url。 似乎我什至無法抓住 h1,它會打開一個新選項卡,然后掛起,然后打開同一個選項卡。
先感謝您!
from selenium import webdriver from selenium.webdriver.common.keys import Keys import time driver = webdriver.Chrome() driver.get('https://zdb.pedaily.cn/enterprise//') #main URL title_links = driver.find_elements_by_css_selector('ul.n4 a') urls = [] #list of URLs # main = driver.find_elements_by_id('enterprise-list') for item in title_links: urls.append(item.get_attribute('href')) # print(urls) for url in urls: driver.execute_script("window.open('');") driver.switch_to.window(driver.window_handles[1]) driver.get(url) print(driver.find_element_by_css_selector('div.info h1'))
嗯,這里有幾個問題:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
driver = webdriver.Chrome()
driver.get('https://zdb.pedaily.cn/enterprise/') # main URL
# Be much more specific or you'll get multiple returns of the same link
urls = driver.find_elements(By.TAG_NAME, 'ul.n4 li div.img a')
for url in urls:
# get href to print
print(url.get_attribute('href'))
# Inject JS to open new tab
driver.execute_script("window.open(arguments[0])", url)
# Switch focus to new tab
driver.switch_to.window(driver.window_handles[1])
# Make sure what we want has time to load and exists before trying to grab it
WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, 'div.info h1')))
# Grab it and print it's contents
print(driver.find_element(By.CSS_SELECTOR, 'div.info h1').text)
# Uncomment the next line to do one tab at a time. Will reduce speed but not use so much ram.
#driver.close()
# Focus back on first window
driver.switch_to.window(driver.window_handles[0])
# Close window
driver.quit()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.