Python 无法单击地图上的标志
我已经用Python和selenium编写了一个脚本,用于单击地图中可用的每个标志。但是,当我执行脚本时,它在到达此行时抛出Python 无法单击地图上的标志,python,python-3.x,selenium,selenium-webdriver,web-scraping,Python,Python 3.x,Selenium,Selenium Webdriver,Web Scraping,我已经用Python和selenium编写了一个脚本,用于单击地图中可用的每个标志。但是,当我执行脚本时,它在到达此行时抛出timeout exception错误wait.until(EC.staleness\u of(item)) 在点击该行之前,脚本应该点击一次,但它不能?我如何循环点击地图上的所有标志 这是到目前为止我的代码(可能是我使用了错误的选择器): 该地图上可见的标志如下: Post script:我知道这是他们的APIhttps://www.findapetwash.com/
timeout exception
错误wait.until(EC.staleness\u of(item))
在点击该行之前,脚本应该点击一次,但它不能?我如何循环点击地图上的所有标志
这是到目前为止我的代码(可能是我使用了错误的选择器):
该地图上可见的标志如下:
Post script:我知道这是他们的APIhttps://www.findapetwash.com/api/locations/getAll/
使用它我可以获得JSON内容,但我想坚持Selenium的方式。谢谢
我知道你写过你不想使用API,但是使用Selenium从地图标记获取位置似乎有点过分了,相反,为什么不使用请求调用他们的Web服务并解析返回的json呢 下面是一个工作脚本:
import requests
import json
api_url='https://www.findapetwash.com/api/locations/getAll/'
class Location:
def __init__(self, json):
self.id=json['id']
self.user_id=json['user_id']
self.name=json['name']
self.address=json['address']
self.zipcode=json['zipcode']
self.lat=json['lat']
self.lng=json['lng']
self.price_range=json['price_range']
self.photo='https://www.findapetwash.com' + json['photo']
def get_locations():
locations = []
response = requests.get(api_url)
if response.ok:
result_json = json.loads(response.text)
for location_json in result_json['locations']:
locations.append(Location(location_json))
return locations
else:
print('Error loading locations')
return False
if __name__ == '__main__':
locations = get_locations()
for l in locations:
print(l.name)
硒
如果您仍然希望使用Selenium,而不是等待所有元素加载,您可以暂停脚本几秒钟甚至一分钟,以确保所有内容都已加载,这将修复超时异常:
import time
driver.get(link)
# Wait 20 seconds
time.sleep(20)
对于其他可能的解决方法,请参见此处的公认答案:如果由于某些原因无法使用API,则可以使用Selenium逐个单击。还可以提取每个标志的信息,而无需使用Selenium单击它们 此处显示要逐个单击的代码:
signs = wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, "li.marker.marker--list")))
for sign in signs:
driver.execute_script("arguments[0].click();", sign)
#do something
不必等待也可以尝试,可能会奏效。OP明确表示,他们宁愿不使用API,而坚持使用Selenium Edit:现在解决了,我似乎知道了,但代码伤了我的眼睛,所以我编写了一个更加防弹的解决方案。不过我补充了一句话,谢谢。使用API绝对是更优雅的方式,同意我不认为你可以,那些符号不是html的一部分。作为一种解决方法,您可以打开右侧的列表并单击其中的项目,但是如果这不仅仅是为了练习,我认为API是您最好的解决方案。
signs = wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, "li.marker.marker--list")))
for sign in signs:
driver.execute_script("arguments[0].click();", sign)
#do something