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

2024-09-30 01:36:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用Python中的selenium webdriver从公共站点http://www.seaaroundus.org获取数据。我试图使用下面的代码来获取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)

Tags: thepath项目org文本importhttp网页
1条回答
网友
1楼 · 发布于 2024-09-30 01:36:01

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

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"]))

相关问题 更多 >

    热门问题