特定类别下的网站层级抓取
我正在尝试抓取这个页面:“https://esco.ec.europa.eu/en/classification/skill_main”。特别是,我想点击所有“S技能”下的加号按钮,直到没有更多的“加号”可以点击,然后保存这个页面的内容。现在,我发现加号按钮在页面的CSS选择器是“.api_hierarchy.has-child-link”,所以我尝试了以下代码:
from selenium.common.exceptions import StaleElementReferenceException
driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))
driver.get("https://esco.ec.europa.eu/en/classification/skill_main")
driver.implicitly_wait(10)
wait = WebDriverWait(driver, 20)
# Define a function to click all expandable "+" buttons
def click_expand_buttons():
while True:
try:
# Find all expandable "+" buttons
expand_buttons = wait.until(EC.presence_of_all_elements_located(
(By.CSS_SELECTOR, ".api_hierarchy.has-child-link"))
)
# If no expandable buttons are found, we are done
if not expand_buttons:
break
# Click each expandable "+" button
for button in expand_buttons:
try:
driver.implicitly_wait(10)
driver.execute_script("arguments[0].click();", button)
# Wait for the dynamic content to load
time.sleep(1)
except StaleElementReferenceException:
# If the element is stale, we find the elements again
break
except StaleElementReferenceException:
continue
# Call the function to start clicking "+" buttons
click_expand_buttons()
html_source = driver.page_source
# Save the HTML to a file
with open("/Users/federiconutarelli/Desktop/escodata/expanded_esco_skills_page.html", "w", encoding="utf-8") as file:
file.write(html_source)
# Close the browser
driver.quit()
但是,上面的代码一直在打开和关闭“第一层”的加号,这可能是因为我对抓取的知识有限,我只是让selenium点击加号按钮,直到没有加号为止。当页面刷新回原来的状态时,脚本就一直重复这个操作,导致无限循环。现在我的问题是:我该如何只打开所有S技能的加号(直到没有加号为止):
<a href="#overlayspin" class="change_right_content" data-version="ESCO dataset - v1.1.2" data-link="http://data.europa.eu/esco/skill/335228d2-297d-4e0e-a6ee-bc6a8dc110d9" data-id="84527">S - skills</a>
?
提前谢谢你,如果我没有进一步说明很抱歉,但我觉得我在抓取方面遇到了瓶颈。
1 个回答
1
我觉得这对你会有帮助,虽然我没测试过。不过你自己写的代码也很用心。
我对XPATH了解得更多,所以把CSS选择器换成了XPATH。
其他的代码应该是一样的,应该可以正常工作。
# Find all expandable "+" buttons
expand_buttons = wait.until(EC.presence_of_all_elements_located(
(By.XPATH, "//div[@class='main_item classification_item' and ./a[text()='S - skills']]//span[@class='api_hierarchy has-child-link']"))
)