Skip to main content
 首页 » 编程设计

python之在 Python 中使用 Selenium 从部分可见的滚动框中抓取所有文本

2025年01月19日8java哥

我正在尝试从公共(public)站点抓取数据 http://www.seaaroundus.org在 Python 中使用 selenium-webdriver。我正在尝试抓取 this 上列表选项的值使用以下代码的网页。该列表位于滚动框内并且部分可见。当我从 xpath 中提取文本时,它只返回列表中的前 11 项。有没有办法提取列表中所有项目的文本?我试图遍历不同项目的 xpath,但它们似乎在每第 11 个项目之后重复,因此循环中断。我必须为大约 300 个类似的网页执行此操作。将不胜感激任何线索! Screenshot here

import time 
from selenium import webdriver 
 
chrome_path = "C:\Program Files (x86)\chromedriver.exe" 
driver = webdriver.Chrome(chrome_path) 
 
#1 open website 
driver.get("http://www.seaaroundus.org/data/#/eez/8/exploited-organisms") 
time.sleep(5) 
 
#xpath of where all the taxa names are listed 
x_path = """//*[@id="exploited-organisms"]/sau-taxon-grid/div[2]/div[1]""" 
 
#printing the xpath.text only prints the first 11 items 
print(driver.find_element_by_xpath(x_path).text) 

请您参考如下方法:

正如@Florent B. 正确建议的那样,您可以简单地使用对 API 的直接 HTTP 请求来获取所需的数据:

import requests 
import json 
 
url = 'http://api.seaaroundus.org/api/v1/eez/exploited-organisms/?region_id=8' 
 
response = requests.get(url) 
 
for fish in response.json()['data']: 
    print("{} ({})".format(fish["common_name"], fish["scientific_name"]))